Friday, November 4, 2011

String (line) I/O in Files in C programming language

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 !
Note that each string is terminated by hitting enter. To terminate the execution of the program, hit enter at the beginning of a line. This creates a string of zero length, which the program recognizes as the signal to close the file and exit.
We have set up a character array to receive the string; the fputs( ) function then writes the contents of the array to the disk. Since fputs( ) does not automatically add a newline character to the end of the string, we must do this explicitly to make it easier to read the string back from the file.
Here is a program that reads strings from a disk file.
/* Reads strings from the file and displays them on screen */
#include "stdio.h"
main( )
{
FILE *fp ;
char s[80] ;
fp = fopen ( "POEM.TXT", "r" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit( ) ;
}
while ( fgets ( s, 79, fp ) != NULL )
printf ( "%s" , s ) ;
fclose ( fp ) ;
}
And here is the output...
Shining and bright, they are forever,
so true about diamonds,
more so of memories,
especially yours !
The function fgets( ) takes three arguments. The first is the address where the string is stored, and the second is the maximum length of the string. This argument prevents fgets( ) from reading in too long a string and overflowing the array. The third argument, as usual, is the pointer to the structure FILE. When all the lines from the file haave been read, we attempt to read one more line, in which case fgets( ) returns a NULL

No comments:

Post a Comment