In the last tutorial I told you about the file copy program using file input output functions. From the last two tutorials you must have noticed that the base of the program is same for all but we are making just simple twist to do our desired task. There are unlimited possibilities using file input output function. I have already discussed two in the last two tutorials. Today I will tell you about another useful program to do file input output using Strings. And this will be the last program of this topic.
File Handling in C
String Input/Output in Files
Till now we are doing input output by using character. However in practical we often use strings instead of characters one by one. In this program I will use a new function whose name is fputs(). Oh Yes you are right! This function will be used to write strings of characters on files. So lets build one program for that.
#include<stdio.h> #include<stdlib.h> #include<string.h> void main() { FILE *fp; char p[80]; fp=fopen("demo.txt","w"); if(fp==NULL) { puts("Cannot open file"); exit(0); } printf("nEnter the text to write on filen"); while(strlen(gets(p))>0) { fputs(p,fp); fputs("n",fp); } fclose(fp); }
Output
Above program will write strings of characters in the file Demo.txt
Explanation
1). In starting I have declared one FILE pointer fp and string p() whose length is 80 characters.
2. After that I have opened the file in “w” mode. This will check the file on the disk. If it is present then it will open it otherwise it will create a file with given name and extension.
3. If the file can’t be accessed then it will display a message “cannot open a file”.
4. After that I have placed one printf() function to inform the user to write down some strings.
5. Now I have created one infinite loop and I have used strlen() function to exit the program if the user press Enter key two times simultaneously.
6. Inside the while loop I have used fputs() function to write down the strings in file.
Let us make one program to see how to read string from file.
#include<stdio.h> #include<stdlib.h> void main() { FILE *fp; char p[80]; fp=fopen("demo.txt","r"); if(fp==NULL) { puts("Cannot open file"); exit(0); } while(fgets(p,'n',fp)!=NULL) { puts(p); } fclose(fp); }
Output
It will display the content of file demo.txt.
Explanation
I have opened the file demo.txt in read mode. Now I am reading the strings from the file using fgets() function. As you can see I have used ‘n’, it means fgets() will read a string till new line is encountered. When fgets() can’t find anymore string then it will return NULL and this will be the end of file.
You can find more C programs on file handling here.