CFile and reading data

This is a discussion on CFile and reading data within the Windows Programming forums, part of the Platform Specific Boards category; Hi all I am trying to get to grips with file handling under MFC and it has me slightly baffled. ...

  1. #1
    Registered User filler_bunny's Avatar
    Join Date
    Feb 2003
    Posts
    87

    CFile and reading data

    Hi all

    I am trying to get to grips with file handling under MFC and it has me slightly baffled. I am using a CFile object to interface with the file - but my problem is that the buffer reads the entire 1024 bytes.. This of course has the nasty side effect of printing garbage in the messagebox. Is there a better way of reading the file such that you only read the data in the file?
    Code:
      BYTE buffer[0x0400];	// 1KB buffer
      CFile file (_T("File.txt"), CFile::modeRead);
      DWORD dwBytesRemaining = file.GetLength();
    
      while(dwBytesRemaining)
      {
          UINT nBytesRead = file.Read(buffer, sizeof(buffer));
          dwBytesRemaining -= nBytesRead;
      }
    
      MessageBox((char*)buffer);
    Thanks.

  2. #2
    Registered User filler_bunny's Avatar
    Join Date
    Feb 2003
    Posts
    87
    I have just been playing with this code and realised it is possible that the problem is I am trying to read a text file using the wrong functions and data types. Is it possible to effectively read a text file using a CFile object with a BYTE array or is it advisable to only read binary data in this fashion?
    Code:
      CStdioFile file (_T("File.txt"), CStdioFile::modeRead);
      CString buffer;
      CString string;
    
      while (file.ReadString(buffer))
          string += buffer;
    
      MessageBox(string);
    Last edited by filler_bunny; 02-11-2003 at 03:48 AM.
    Visual C++ .net
    Windows XP profesional

  3. #3
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    Here's an example of what you are trying to do....you can use CFile::Read....but CStdioFile::ReadLine workds too

    You need to observe MFC exception handling for both the constructor and the ReadLine.......also...you can then use a CString which makes the memory allocation simple....

    Exceptions in MFC are horrible...they are created on the heap and thrown as pointers....so you must manually delete them....far simpler to throw a reference to a stack based exception in my opinion (and also that of people like Scott Meyers), but this is how MFC is made, so you must call CException::Delete on the exception pointer to avoid a memory leak

    Code:
    void CTestMFCDlg::Read()
    {
    	try
    	{
    	
    		CStdioFile file(_T("File.txt"), CFile::modeRead);
    		CString str,mainstr = _T("");
    
    		while(file.ReadString(str))
    		{
    			mainstr += str;
    			mainstr += _T("\n");
    		}
    		MessageBox(mainstr);
    	}
    	catch(CException* e)//Catch by pointer as exceptions in MFC are crap
    	{
    		MessageBox(_T("Error - unable to open file"));
    		e->Delete();//Lame...very lame...but needed
    
    	}
    
    }

  4. #4
    Registered User filler_bunny's Avatar
    Join Date
    Feb 2003
    Posts
    87
    Thanks Fordy, that is excellent. I understand that fully. But I now have to understand why I cannot achieve the same results using CFile.

    I think my problem is that I am somewhat stubborn, and I must understand why something doesn't work. I am attempting to retry the code using the CFile class and the CFile::Read method. Similar operations should work so I have just edited the code snippet Fordy provided:

    This is what is in my data file (File.txt):
    This file contains data
    This file contains data
    This file contains data
    This file contains data
    This file contains data
    This file contains data
    This file contains data
    This file contains data
    This file contains data
    Code:
        try
       {
            CFile file(_T("File.txt"), CFile::modeRead);
            CString mainstr = _T("");
            char buffer[10];
        
            while(file.Read(buffer, sizeof(buffer)))
            {
                 TRACE(_T("%s"),buffer);
                 mainstr += buffer;
                 mainstr += _T("\n");
            }
            MessageBox(mainstr);
        }
        catch(CException* e)
        {
            MessageBox(_T("Error - unable to open file"));
            e->Delete();
        }
    And this is the debug output - which leads me to believe I am touching memory I shouldn't somewhere.
    This file面面面面面$.|面面面面l3|| contains面面面面面 data
    Th面面面面面is file c面面面面面ontains d面面面面面ata
    This面面面面面 file con面面面面面tains dat面面面面面a
    This f面面面面面ile conta面面面面面ins data
    面面面面面
    This fil面面面面面e contain面面面面面s data
    T面面面面面his file 面面面面面contains 面面面面面data
    Visual C++ .net
    Windows XP profesional

  5. #5
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    Remember that CFile::Read is a raw operation....it doesnt NULL of the buffer it retrieves

    Have a look at this;

    Code:
    void CTestMFCDlg::Read()
    {
        try
       {
            CFile file(_T("File.txt"), CFile::modeRead);
            CString mainstr = _T("");
            char buffer[10];
    		UINT unRead;
       
    		unRead = file.Read(buffer, sizeof(buffer)-1);
            while(unRead)
            {
    			buffer[unRead] = '\0';
                TRACE(_T("%s"),buffer);
                mainstr += buffer;
                mainstr += _T("\n");
    			unRead = file.Read(buffer, sizeof(buffer)-1);
            }
            MessageBox(mainstr);
        }
        catch(CException* e)
        {
            MessageBox(_T("Error - unable to open file"));
            e->Delete();
        }
    
    }

  6. #6
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    Also, dump the " mainstr += _T("\n");" line....Read will add the newline from the file

    And maybe make the read buffer bigger...this will result in less function calls

  7. #7
    Registered User filler_bunny's Avatar
    Join Date
    Feb 2003
    Posts
    87
    Thank you, Thank you. I got it.

    Thanks again for the help.
    Visual C++ .net
    Windows XP profesional

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Am i doing this right? (file reading)
    By RancidWannaRiot in forum Windows Programming
    Replies: 3
    Last Post: 09-21-2005, 09:11 PM
  2. How can I do the following..
    By Dual-Catfish in forum C++ Programming
    Replies: 14
    Last Post: 05-01-2002, 03:38 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21