Question

Im wriitng some data in File.But it doesnot write this properly. Code:

CString sFileName = "C:\\Test.txt";
CFile gpFile;

    CString testarr[10] = {"Tom","Ger","FER","DER","SIL","REM","FWE","DWR","SFE","RPOP"};

    if (!gpFile.Open( sFileName,CFile::modeCreate|CFile::modeWrite))
    {
        AfxMessageBox( sFileName + (CString)" - File Write Error");      
        return;
    }
   else
   {
      gpFile.Write(testarr,10);
   }

    AfxMessageBox("Completed");
    gpFile.Close(); 

It shows the file as enter image description here

Was it helpful?

Solution

That's probably because you're using CFile incorrectly. The first parameter to CFile::Write should be a buffer whose bytes you'd like to write to the file. However, testarr is more like a "buffer of buffers", since each element of testarr is a string, and a string is itself a sequence of bytes.

What you would need to do instead is either concatenate the elements of testarr, and then call CFile::Write. Or (probably more practical), iterate over testarr printing each string one at a time, e.g. for your particular example, the following should do what you're looking for:

for(int i = 0; i < 10; ++i)
{
    gpFile.Write(testarr[i], strlen(testarr[i]));
}

There may be some built-in way to accomplish this, but I'm not really familiar with MFC, so I won't be much help there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top