String (line) I/O in Files in C

For many purposes, character I/O is just what is needed. However, in some situations the usage of functions that read or write entire strings might turn out to be more efficient.

Reading or writing strings of characters from and to files is as easy as reading and writing individual characters. Here is a program that writes strings to a file using the function fputs( )

/* Receives strings from keyboard and writes them to file */ 
#include "stdio.h" 
main( ) 
{ 
 FILE *fp ; 
 char s[80] ;
fp = fopen ( "POEM.TXT", "w" ) ; 
 if ( fp == NULL ) 
 { 
 puts ( "Cannot open file" ) ; 
 exit( ) ; 
 } 
 printf ( "\nEnter a few lines of text:\n" ) ; 
 while ( strlen ( gets ( s ) ) > 0 ) 
 { 
 fputs ( s, fp ) ; 
 fputs ( "\n", fp ) ; 
 } 
 
 fclose ( fp ) ; 
} 

And here is a sample run of the program…

Enter a few lines of text:
Shining and bright, they are forever,
so true about diamonds,
more so of memories,
especially yours !

Leave a Comment