Thread: Problem with loading a file

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    15

    Problem with loading a file

    I currently have this code for loading the contents of a file in a function,

    Code:
    	
    void loadfile1() 
    	{ 
    		string line;
    
    		cout << "File 1 - \n \n";
    		ifstream infile("test.txt", ios::in); 
    		while( !infile.eof() ) 
    		{ 
    			getline (infile,line);
    			cout << line << endl;
    		} 
    		infile.close( ); 
    	}
    This code works fine when there is data in the file, but when there isn't it goes into an infinite loop.
    I have tried a few things to fix it, but I think I just made it worse. Any ideas?

    Thanks in advance.

  2. #2
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    Code:
    string getfile()
    {
    	string line;
    	string file;
    
    	ifstream in ( "test.txt" );
    
    	while ( getline( in, line ) )
    		file += line + "\n";
    
    	in.close();
    
    	return file;
    }
    should return the whole file. Use it as follows:

    Code:
    int main( void )
    {
    	string test_file = getfile();
    
    	cout<< test_file;
    
    	return 0;
    }
    Obviously, I'm being dangerously minimalist with my error checking here. It's a bad idea to do that, so I'll leave it to you to add that in.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> This code works fine when there is data in the file, but when there isn't it goes into an infinite loop.
    That's because an empty file will cause the file stream to go into a fail state when you attempt to read with getline. You never check for a failed read, you only check for eof. You should use while (getline (infile,line)).

    BTW, twomers' getfile function would probably be better using the method shown in this post: http://cboard.cprogramming.com/showp...23&postcount=5

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  2. Problem reading file
    By coder_009 in forum C Programming
    Replies: 10
    Last Post: 01-15-2008, 01:22 PM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Replies: 6
    Last Post: 03-06-2005, 02:43 PM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM