'Reading a file and print the content in C

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.



Solution 1:[1]

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 = malloc(size + 1);               // +1 for the null terminator
size_t chars_read = fread(content, 1, size, f); // store the returned value
content[chars_read] = '\0';                     // add null terminator
printf("File content is...\n%s\n", content);    // now ok to print

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1