Thread: CFile and reading data

  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 04:48 AM.
    Visual C++ .net
    Windows XP profesional

  3. #3
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    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,793
    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,793
    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