I'm learning how to write and read files in C, and I wrote a text using this code
FILE *f = fopen("testingText.txt", "w");
char *text = "This is text1...";
fwrite(text, sizeof(char), strlen(text), f );
fclose(f);
and when I read the content of this file and print it using this code
FILE *f = fopen("testingText.txt", "r");
fseek(f, 0, SEEK_END);
unsigned int size = ftell(f);
fseek(f , 0, SEEK_SET);
char *content = (char *)malloc(size);
fread(content, sizeof(char), size, f);
printf("File content is...\n%s", content);
free(content);
fclose(f);
it gives the result with strange things like these
File content is... This is text1...Path=C:*┬#æ╩eò*
and when I run the code again it gives different strange things.
CodePudding user response:
There is no null terminator in the file so you'll need to add that manually before printing what you've read from the file.
Example:
char *content = (char *)malloc(size 1); // 1 for the null terminator
size_t chars_read = fread(content, sizeof(char), size, f);
if(chars_read > 0) {
content[chars_read] = '\0'; // add null terminator
printf("File content is...\n%s", content);
}
CodePudding user response:
The following line is wrong:
printf("File content is...\n%s", content);
Using printf with the %s conversion format specifier requires a null-terminated string. However, your string is not null-terminated.
In order to print a sequence of characters that is not null-terminated, you can write the following instead:
printf("File content is...\n%.*s", (int)size, content);
Or you can add a terminating null character manually, with the following line:
content[size] = '\0';
However, this will write to the memory buffer content out of bounds, because you did not allocate any space for the null terminating character. Therefore, you should allocate one additional byte in the malloc function call.
Another problem is that using ftell is not a reliable way to determine the length of the file. For example, on Microsoft Windows, this will give you the length of the file in binary mode (even when the file is opened in text mode). However, the length of the file in text mode is different, because \r\n line endings get translated to \n on Micrsoft Windows.
Therefore, if you want to read the content of a text file of unknown length, it would probably be better to read one line at a time in a loop, using the function fgets.
