Shabbir Hussain
Shabbir Hussain

Reputation: 2720

CFile reads 0 bytes

When using a CFile, for Some reason my call to read() returns 0 bytes after the first call

CFile iniFile;
int bytesRead=0;
char buffer[_MAX_PATH]; 
if(iniFile.Open(iniDirFilename,CFile::modeRead)){
        bytesRead += iniFile.Read(buffer,_MAX_PATH); // read file path
        SaveDirectoryBox->SetWindowTextA(buffer);
        iniFile.Seek(bytesRead,CFile::begin); // reposition pointer

        int x =iniFile.GetLength();
        int y =iniFile.GetPosition();




        bytesRead += iniFile.Read(buffer,_MAX_PATH); // read subfile path
        subSaveDirectoryBox->SetWindowTextA(buffer);
        iniFile.Seek(bytesRead,CFile::begin); // reposition pointer
}

It shows me that the file length is only 72 bytes when I know it is clearly more. I saved a bunch of null terminated strings. For example "Hello" I suspect that upon construction the CFile class looks for the first NULL character and calls it the end of file. I tried using the setLength() function but that gives me an error

How can I read the rest of the file?

edit:

I should mention that I have my project set to read an write in ascii. And the file is written in ascii too

Upvotes: 1

Views: 1384

Answers (1)

JohnCz
JohnCz

Reputation: 1609

If you have file with zero terminated string, you should treat it as binary rather than text. This is one of possible solutions that will read string from the beginning to the next terminating zero character.

    ULONGLONG iTotalBuffSize = 0;
    CFile iniFile(_T("TestFile.txt"), CFile::modeRead);

    iTotalBuffSize = iniFile.GetLength();

    TCHAR* pBuff = new TCHAR[(UINT)iTotalBuffSize];

    iniFile.Read(pBuff, (UINT)iTotalBuffSize);

    while(0 != *pBuff)
    {
        CString csText(pBuff);   // this is your n-th string
        TRACE(_T("%s\n"), csText);

        pBuff += csText.GetLength() + sizeof(TCHAR);
    }

I wrote this using generic text mapping so the code can be used in both UNICODE and ANSI app.

Upvotes: 1

Related Questions