Thread: Read more than one line in a file

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #5
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    If you want to read the whole file, just use fread():
    Code:
    #include <stdio.h>
    #include <malloc.h>
    
    int main()
    {
    	long length;
    	char* buf;
    	size_t bytes;
    	FILE* file = fopen( "c:/file.txt", "rb" );
    
    	if ( file == NULL )
    	{
    		printf( "Error opening file!" );
    		return 1;
    	}
    
    	if ( fseek( file, 0, SEEK_END ) != 0 )
    	{
    		fclose( file );
    		printf( "fseek() failed!" );
    		return 2;
    	}
    
    	if ( (length = ftell( file )) < 0 )
    	{
    		fclose( file );
    		printf( "ftell() failed!" );
    		return 3;
    	}
    
    	if ( fseek( file, 0, SEEK_SET ) != 0 )
    	{
    		fclose( file );
    		printf( "fseek() failed!" );
    		return 2;
    	}
    
    	if ( (buf = malloc( length + 1 )) == NULL )
    	{
    		fclose( file );
    		printf( "malloc() failed!" );
    		return 4;
    	}
    
    	if ( (bytes = fread( buf, 1, length, file )) != (size_t)length )
    	{
    		free( buf );
    		fclose( file );
    		printf( "fread() didn't read &#37;d bytes!", length );
    		return 5;
    	}
    
    	fclose( file );
    	buf[length] = '\0';
    	printf( "Text file contents:\n%s", buf );
    	free( buf );
    
    	return 0;
    }
    Last edited by cpjust; 08-26-2007 at 03:17 PM. Reason: Oops, forgot to free( buf )...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OPen a file and read it from the last line
    By c_geek in forum C Programming
    Replies: 14
    Last Post: 01-26-2008, 06:20 AM
  2. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  3. getline function to read 1 line from a text file
    By kes103 in forum C++ Programming
    Replies: 3
    Last Post: 10-21-2004, 06:21 PM
  4. how can i read i line from a file
    By condorx in forum C Programming
    Replies: 2
    Last Post: 05-07-2003, 02:47 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM