Re: The contents of the file is not read..
On Tue, Nov 07, 2006 at 06:19:59PM +0530, Naga Priya .K wrote:
> i'm a beginner in C. I used the following code to read and print the
> strings in a file. but the control doesn't reach inside the while
> loop. what is the problem?
The problem is that you don't initialise things correctly. You
test against "EOF" but don't set it anywhere.
> FILE *FilesRead=fopen("FilesRead.txt","r");
> if(!FilesRead)
> printf("File not opened");
> else
> printf("Opened file");
This is wrong, since if the file open fails you still continue.
Try this:
FILE *f = fopen( "FilesRead.txt", "r" );
if ( !f )
{
printf(" Failed to open file\n" );
exit( 1 );
}
> while(!EOF)
> {
> fscanf(FilesRead,"%s",name_read);
> printf("%s",name_read);
> }
> fclose(FilesRead);
You don't change EOF so this will most likely not work. Try this:
while( ! feof( f ) )
{
..
}
Note that you don't define name_read, and you also don't take into
account what will happen if "too much" is read.
See attached version beneath my sig for a working, albeit not
attractive, program.
In the future these questions would be better posted in the comp.lang.c
newsgroup or similar .. since they are not debian-specific.
Steve
--
# The Debian Security Audit Project.
http://www.debian.org/security/audit
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char *argv[] )
{
char line[1024];
FILE *f = fopen( "FilesRead.txt", "r" );
if ( !f )
{
printf(" Failed to open file\n" );
return 1;
}
while( ! feof( f ) )
{
/* Fill buffer with NULL, and make sure we don't read more than 1000
characters. Buffer overflow protection. */
memset( line, '\0', sizeof(line ) );
fscanf( f, "%1000s", &line );
printf( "Read: %s\n", line );
}
fclose( f ) ;
return 0;
}
Reply to: