vendredi 30 octobre 2015

Solaris append data into binary file

The configuration is listed below: Sun C5.12 SunOS_i386 2011/11/16 Oracle Solaris Studio 12.3

We try to append data at the end of a binary file with ofstream class. Original code is here:

unsigned long uRes = 0;
std::ofstream binFile;
binFile.open(filename.c_str(), ios::out | ios::binary | ios::app);
if(!binFile.fail())
{
    binFile.seekp(0, ios::end); // Useless regarding ios::app flag ?
    binFile.write(reinterpret_cast<char*>(&mVector[0]), mVector.size() *  sizeof(T));
    if( binFile.good())
    {
        uRes  = static_cast<unsigned long>(binFile.tellp() / sizeof(T));
    }
}
return uRes;

But under Solaris, writing pointer is always set at the beginning of the output file (data is only overridden).. So we wrote the same function in C mode:

unsigned long uRes = 0;
FILE* pFile = NULL;
pFile = fopen(filename.c_str(), "a+b");
if( pFile )
{
    fseek( pFile, 0, SEEK_END );  // SEEK IS MANDATORY (flag "a" isn't interpreted)
    fwrite(&mVector[0], sizeof(T)*mVector.size(), 1, pFile);
    uRes = ftell( pFile )/ sizeof(T);
    fclose ( pFile );
}
return uRes;

This code works only if we seek manually after opening the file ("a" flag is ignored)

Is there a logic explanation about that? I think there is a lot of problems with stream. For example stream destructor doesn't close pointed file (close should be called directly to be sure that file is correctly closed (with stream operation)) But it is another subject.

Thanks in advance for your feedback

Aucun commentaire:

Enregistrer un commentaire