gpt4 book ai didi

c - 动态字符缓冲区 C

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:44:31 26 4
gpt4 key购买 nike

下面是我的代码的一部分,用于从文本文件中读取数据,去除 HTML 并仅打印出普通文本。这一切都很好,但我在阅读所有文本文件时遇到问题。我将如何阅读整个文本文件,了解我可能需要使用 malloc 但不确定如何使用。

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);

最佳答案

如果您想阅读完整的文件,请执行以下操作:

  1. 打开文件
  2. 使用 fstat - 参见 fstat - 获得尺寸
  3. malloc 缓冲区,即 buffer = malloc(fileStats.st_size);
  4. 读取文件fread(buffer, fileStats.st_size, 1);
  5. 关闭文件。
  6. 随心所欲地玩缓冲区。

您可能希望将缓冲区大小加一以将空字符放入其中。

关于c - 动态字符缓冲区 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9444632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com