I am writing a string to a file. But only the first part of the string is only inserted to file. Others are missing. For eg: If I write "I Like Flowers", "I" is only written into file.
#include <stdio.h>
int main()
{
char string[50];
int marks,i,n;
FILE *fptr; fptr=(fopen("string.txt","w"));
if(fptr==NULL){
printf("Error!");
return 0;
}
printf("Enter a string : \n");
scanf("%s", string);
//fprintf(fptr,"%s",string);
fwrite(string, 1, sizeof(string), fptr);
fclose(fptr);
return 0;
}
The
scanf()
will stop reading at the first space: that is the problem. Thescanf("%s")
only reads theI
from standard input. To read the entire line usefgets()
instead. Usestrlen()
to write only what was read instead of usingsizeof(string)
.