String I/O includes fgets(), fputs()functions. Those functions we are going to discuss in this blog.
fputs()
This function is used to write any string into a file. After writing any string (or reading), the pointer will point to the next location. Below is the syntax for fputs function.
fputs(“<string that we want to write>”,<file pointer name>);
Suppose we want to make file pointer fp1 to point to a text file having the name f1.txt. and we want to write apple into file f1.txt then below is an example of fputs syntax.
Ex.
fputs(“apple”,fp1);
fgets()
This function is used to read any string from a file. This will read the string from the file from that location, which file pointer is pointing. With this also we can use the rewind function if we want. But this will add a NULL character automatically at the end of the string. So if we want to read m characters then write syntax to read m+1 characters.
fgets(<character array> ,n<number of character that we want to read from file>,<file pointer name>);
If we use the same previous example then below is the syntax for fgets. And c is a character array and n is 4 because we want to read 3 characters (4th character will be NULL) from the file. After using the below syntax if we print the value of c then it will print the string of 3 characters from the location which is pointed by file pointer fp1.
Ex.
fgets(c,4,fp1);
Example program structure to understand the use fputs and fgets
In the below example, f1 is a file name and fp1 is a file pointer. First, we have used fopen with mode w+ because we want to write using fputs and read using fgets. Then we have used fputs to write the string “ABCDEF” in the f1 file. Now pointer fp1 is pointing to the location after “ABCDEF“ because it has already written “ABCDEF” at that location so now it is pointing to the location after “ABCDEF”. So to read from the start of the file, we are using a rewind function and we are reading 3 characters from the file. So it will print “ABC ” at the output which is shown below.
#include<stdio.h> #include<conio.h> void main() { char c[10]; FILE *fp1; clrscr(); fp1=fopen("f1.txt","w+"); fputs("ABCDEF",fp1); rewind(fp1); fgets(c,4,fp1); printf("string = %s ",c); fclose(fp1); getch(); }
Learning from this blog:
- What is the need of fputs?
- The syntax for fputs.
- What is needed
- The syntax for fgets.
- Write a program using fputs and fgets.
Kudos to author for creating such informative blog.