I’m trying to read from a text file using the read function and store to a buffer. I then have to check the file again to see if any changes were made, and if there are, to reallocate memory and store contents to the same buffer (appending), character by character until EOF is reached. My code looks like this so far:
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*/
I tried a lot of things, but always end up having problems when I try to append the contents from “tempChar” to “buf”. I know to use the realloc function..but I’m still having problems. Any help would be appreciated.
Thanks!
You cannot use
realloc()for statically allocated memory.If you wan to do that, you have to use pointers and allocate the memory dynamically.
Example: