In above code we were reading each char from the file pointer, we can read one string by using fgets(), this is required when one line of data is to be collected. Check the exercise at the end of this page.
#include <stdio.h>
int main(void){
FILE *fpt; // File pointer
char c;
fpt=fopen("data1.dat","w"); // Opening file in write mode
fprintf(fpt,"welcome to my file");
fprintf(fpt,"\n Next Line ");
fclose(fpt);
return 0;
}
Writting string to File
We can enter one line of code at a time and hit enter to complete the line. Each line is checked for its length by using strlen() and once we enter twice enter key the length of line will be equal to 0 and the while loop will terminate.
So hit enter twice to end the entry of line of text to file.
#include <stdio.h>
#include <string.h>
int main(void){
FILE *fpt;
char str[100];
fpt=fopen("data4.dat","w");
if(fpt==NULL)
printf("Can't open file ");
else {
printf("Enter one line of text\n");
while(strlen(gets(str))>0){
fputs(str,fpt);
fputs("\n",fpt);
}
}
fclose(fpt);
return 0;
}
File Append
We can add text and end of the file by opening the file in appending mode.
#include <stdio.h>
int main(void){
FILE *fpt;
char c;
fpt=fopen("data1.dat","a");
fprintf(fpt,"\n my new line ");
fprintf(fpt,"\n my new Next Line ");
fclose(fpt);
return 0;
}