I am creating a file with the content depending on some local variables. I don’t know how long the file will be at the end. Since I define a buffer[] array with a fixed size, the last characters in the generated file are garbage. How should I trim buffer[] array before writing it to the file? Or fwrite only the used bytes?
Here is my code:
FILE * pFile = NULL;
char buffer[300];
int ret_val = -1;
strcpy_s(buffer, "The path is \"");
strcat_s(buffer, pathVariable);
strcat_s(buffer, "\"\n");
pFile = fopen(myfile, "w");
if(NULL == pFile)
{
perror("File opening error");
return -1;
}
ret_val = fwrite(buffer, 1, sizeof(buffer), pFile );
if(sizeof(buffer) != ret_val)
{
perror("File writing error");
return -1;
}
fclose(pFile);
fwrite()doesn’t know which bytes you consider “used”. When you call it like so:it will write
sizeof(buffer)bytes.Change the call to:
where
used_bytesis some variable that you set before the call.You’ll also need to alter the subsequent error check:
edit In this case, it would appear you’d want to set
used_bytestostrlen(buffer).