I am a beginner in C language and I'm trying to learn about file handling with functions such as fread() and fwrite(), but there is a problem when I read a string from a file and output it using printf("%s", var);
this is the program below to test the functions.
#include <stdio.h>
#include <string.h>
void main()
{
FILE *farquivo;
int i;
char text[10];
char file[51] = "string01 string02 string03 string04 string05 ";
farquivo = fopen("dados.txt", "w");
fwrite(file, 1, sizeof(file), farquivo);
fclose(farquivo);
farquivo = fopen("dados.txt", "r");
printf("Sizeof text[] = %d\n", sizeof(text));
printf("Strings by %%s:\n");
fread(text, 1, sizeof(text), farquivo);
printf("%s\n", text);
fread(text, 1, sizeof(text), farquivo);
printf("%s\n", text);
fread(text, 1, sizeof(text), farquivo);
printf("%s\n", text);
fread(text, 1, sizeof(text), farquivo);
printf("%s\n", text);
fread(text, 1, sizeof(text), farquivo);
printf("%s\n", text);
printf("String char by char:\n");
for(i = 0; i < sizeof(text); i++){
printf("%c", text[i]);
}
printf("\n");
fclose(farquivo);
}
Everything seems to be okay but the output is odd, this is the output on the console:
Sizeof text[] = 10
Strings by %s:
string01 `FÛu>
string02 `FÛu>
string03 `FÛu>
string04 `FÛu>
string05 `FÛu>
String char by char:
string05
Process returned 0 (0x0) execution time : 0.051 s
Press any key to continue.
For some reason when i use printf("%s", var);
to print the strings the end of it outputs "`FÛu>" but if I print every char of the string one by one this doesn't happen, am I using it in the right way ?