以下は、テキストファイルからデータを読み込み、HTMLを取り除いて通常のテキストだけを出力するコードの一部です。これはすべてうまく動作しますが、私はすべてのテキストファイルを読むことに問題があります。どのように私はテキストファイル全体を読んで、私はおそらくmallocを使う必要があるが、そのようにする方法がわからないことを理解する。動的文字バッファC
int i, nRead, fd;
int source;
char buf[1024];
int idx = 0;
int opened = 0;
if((fd = open("data.txt", O_RDONLY)) == -1)
{
printf("Cannot open the file");
}
else
{
nRead = read(fd, buf, 1024);
printf("Original String ");
for(i=0; i<nRead; i++)
{
printf("%c", buf[i]);
}
printf("\nReplaced String ");
for(i=0; i<nRead; i++)
{
if(buf[i]=='<') {
opened = 1;
} else if (buf[i] == '>') {
opened = 0;
} else if (!opened) {
buf[idx++] = buf[i];
}
//printf("%c", buf[i]);
}
}
buf[idx] = '\0';
printf("%s\n", buf);
close(source);
'0'が得られるまで' read'呼び出しをループし、読み込んだ量を追跡してバッファに追加する必要があります。バッファは必要に応じて、おそらく 'realloc 'を介して成長する必要があります。 –