读取功能:复制缓冲区,重新分配内存

时间:2011-11-06 22:41:19

标签: c char malloc buffer

我正在尝试使用read函数从文本文件中读取并存储到缓冲区。然后,我必须再次检查文件以查看是否进行了任何更改,如果有,则重新分配内存并将内容存储到同一缓冲区(追加),逐个字符,直到达到EOF。到目前为止,我的代码看起来像这样:

int fileSize=0;
fileSize=fileStat.st_size; /*fileSize is how many bytes the file is, when read initially*/

char buf[fileSize];
read(0, buf, fileSize);

/*now, I have to check if the file changed*/
int reader;
void *tempChar;
int reader=read(0, tempChar, 1);
while(reader!=0){
   /*this means the file grew...I'm having trouble from here*/

我尝试了很多东西,但是当我尝试将“tempChar”中的内容附加到“buf”时,总是遇到问题。我知道使用realloc函数..但我仍然遇到问题。任何帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:1)

您不能将realloc()用于静态分配的内存。

如果你想这样做,你必须使用指针并动态分配内存。

示例:

char *buf;
buf = malloc(fileSize);
相关问题