Reading text files
to read a line from the file you use fgets, which acceps a string, the amount of text to read, and a file pointer
for example
char string[ 128 ];
FILE *pFile = fopen( "myfile.txt", "r" );
fgets( string, 128, pFile );
this will read the first line of the file, up to 128 characters.
Beware, if you declare string as char string[ 16 ], but then you try
and read 128 characters it will read the rest into unclaimed memory
and cause a crash or very weird results.
Now to read multiple lines - we will revisit our friend the while loop :).
fgets is what I use to read each line. It will read up to the new line (\n),
or up to the maximum amount of characters specified. For instance if the first
line of your file is 128 bytes long and you do fgets( string, 16, pFile ) it
will only read the first 16 bytes. The next time you call fgets( string, 16, pFile )
it will read the next 16 bytes, etc. If you call fgets( string, 256, pFile ) it
will read the entire line of 128 bytes and stop there. The next time fgets is called
it will read the next line.
fgets will return the amount of bytes read or NULL (0) if it's the end
of the file. So how do you read through a file? Use the while loop!
while ( fgets( string, 256, pFile ) )
{
printf( "%s\n", string );
}
whoa - what is going on here? This is what we are telling the computer:
while fgets continues to return the amount of bytes read - print out the string
that fgets filled. As soon as fgets returns 0 (no bytes read) the while loop will stop.
__________________________________________________________
#define _CRT_SECURE_NO_DEPRECATE
#include <string.h>
#include <stdio.h>
#include <conio.h>
void main( void )
{
char name[ 128 ];
char filename[ 128 ];
char string[ 256 ];
printf( " Enter file name :" );
scanf( "%s", name );
sprintf( filename, "C:\\%s.txt", name );
FILE *pFile = fopen( filename,"r" );
if ( pFile == 0 )
{
printf( "\n\n File does not exist in this directory." );
}
else
{
while ( fgets( string, 256, pFile ) )
{
printf( "%s", string );
}
}
getch( );
}
|