Re: read an ascii file with fopen
"Mark" <mark@chasan.ar> wrote in message
news:%23sPmEzsgGHA.2208@TK2MSFTNGP05.phx.gbl...
I try to open with fopen and read an ascii file, line by line, but get
garbage - among the right data in the CString variable that is filled
with
this line data.
Can someone copy&paste the right code how to so that?
Thanks in advance.
Mark
When opening the file you need to have a buffer large enough to hold the
string plus the null. How you open the file is important too. MSDN lists
all the open flags for _fopen. The _fopen() function has versions for
defining unicode and multibyte as well.
// ---------------------------------------
// assuming the function returns boolean
FILE *fh; // file handle
char sBuffer[255]; // buffer
CString sLine; // CString var
if((fh=fopen(szFilename, "rb"))==NULL) // (r+, r, a, a+, b etc.)
{
return FALSE; // return failure
}
// loop with EOF and error checking
while(!feof(fh) && !ferror(fh))
{
fgets(sBuffer, 255, fh); // read string into buffer
sLine = sBuffer; // CString now holds string
sBuffer[0] = '\0'; // clear buffer
// do something useful with CString here
}
fclose(fh); // close handle
return TRUE; // return success
// ---------------------------------------
Also take a look at CStdioFile class and CStdioFile::ReadString()
function in the MSDN Library. One version of ReadString stores the
newline char and the other does not.
HTH
Mark F