views:

115

answers:

1

Hi there,

I need to read a textfile and store the data into a Safearray.

I tried it with this function:

bool Parse::LoadTxtFileIntoSafearray(string* strPath, SAFEARRAY** pByteArray)
{
bool bReturn = false;

string line;
int iOffset = 0;
char* pcBuffer = NULL;

std::ifstream infile ( strPath->data() );
if ( !infile.fail() )
{
    infile.seekg(0, std::ios::end);
    int iSize = infile.tellg();
    infile.seekg(0);
    pcBuffer = (char*)calloc(iSize,sizeof(char));
    if(pcBuffer)
    {
        infile.read(pcBuffer, iSize);
        iSize = strlen(pcBuffer);
        SAFEARRAYBOUND sb;
        sb.cElements = iSize;
        sb.lLbound = 0;
        *pByteArray = SafeArrayCreate(VT_UI1,1,&sb);

        BYTE* pData;
        SafeArrayAccessData(*pByteArray,(void **)&pData);
        memcpy(pData, pcBuffer,iSize);
        SafeArrayUnaccessData(*pByteArray);
        delete pcBuffer;
        pcBuffer = NULL;
        bReturn = true;
    }
}
return bReturn;
}

The Problem is that the size of the file is bigger than the read bytes...

What is wrong?

regards camelord

A: 

As mentioned in the man-page, read attempts to read upto count bytes. To be sure you read all bytes, you have to loop.

As a side-note: you're not always guaranteed to work with a static file, so assuming that the files-size won't change could get you in trouble (buffer-overrun, not reading the complete file, endless loop).

stefaanv