17.13 – Writing and reading line of text from the files

by subbu on October 17, 2014

Now in this session, we will see how a line of text can be write and read from a file

fputs() function:

  • It is the function used to print a line of text onto the file.
  • It accepts both a string and the file pointer as arguments.
  • It returns the last character written on to the file if operation is successful otherwise returns -1

fputs() in C language

Specification: Accept multiple lines of text from the keyboard and write onto the file “fruits”.

#include<stdio.h>
#include<string.h>
int main()
{
 FILE *p;
 char x[40];
 p=fopen("fruits","w"); /* opening file in write mode */
 printf("Enter the names of fruits:\n");
 printf("type \"exit\" to close..\n");
 while(1)
 {
  gets(x);                 /* reading a string from the keyboard */
  if(strcmp(x,"exit")==0)
    break;
  strcat(x,"\n");
  fputs(x,p);             /* writing a string onto the file */
 }
 fclose(p);
 printf("1 file created");
 return 0;
}

Execution:
Enter the names of fruits:
exit to close..
apple
Goa
grapes
jackfruit
exit

Note: Here “exit” is used as terminating word but not written on the file.

Program explained:
Opened the file “fruits” in write mode
gets() is used to read a line of text from the keyboard
Writing the strings on to the file using fputs() through the file pointer
strsmp(x,”exit”) is used to check for the end of file

fgets() function:

  • It is the function used to read a line of text from the file.
  • It accepts the address of a character array, the length of text has to fetch from the file and the file pointer as arguments.
  • fgets() read the specified length of text from the file and assigns to the character array whose address has sent as argument.
  • It return the string fetched from the file.
  • It returns NULL on reaching the end of file.

fgets() in C language

Specification: Read the text from the file “fruits” line by line and print onto the monitor.

#include<stdio.h>
#include<string.h>
int main()
{
 FILE *p;
 char x[40];
 p=fopen("fruits","r");
 printf("The names of fruits:\n");
 while(1)
 {
   if(fgets(x,40,p)==NULL)
     break;
   printf("%s",x);
 }
 fclose(p);
 return 0;
}

Execution:
The names of fruits:
apple
Goa
grapes
jack fruit

Example explained:
The file “fruits” is opened in read mode.
The strings are fetched from the file one after another using fgets() and printing on to the monitor using printf().
fgets() returns NULL when end of file is reached.
Finally file is closed using fclose()

Previous post:

Next post: