Reputation:
I'm trying to store all text from a text file in a variable. This is the code that does that:
FILE *logData_fp;
logData_fp = fopen("log", "r");
fseek(logData_fp, 0, SEEK_END);
int logData_len = ftell(logData_fp);
char *logData = malloc(logData_len*sizeof(char) + sizeof(char));
fgets(logData, logData_len, logData_fp);
logData[strlen(logData)] = '\0';
fclose(logData_fp);
printf("Log data length: %d\nLog data:\n%s\n", strlen(logData), logData);
The entire program compiles with no errors or warnings.
The text file has a few hundred characters in it, but the strlen() value is 3. It also doesn't print out correctly and just has a weird character on the end.
Where have I messed this up?
Upvotes: 1
Views: 219
Reputation: 32732
You seek to the end to get the file size but don't seek back to the beginning before your read. Add this line after the ftell
call.
fseek(logData_fp, 0, SEEK_SET);
fgets
may not read the entire file. Perhaps you want fread
instead?
Also, the logData[strlen(logData)] = '\0';
assignment won't do what you think it will. strlen
looks for a zero byte as the string terminator, which can resulting in writing past the end of the array if that byte isn't found (and if it is, you don't need to put it there). fgets
may put a zero byte there; fread
won't.
Upvotes: 2