Link to home
Create AccountLog in
Avatar of pbsmbc
pbsmbc

asked on

file overwrtie

Hi,

While writing a file using the following function we are not able to overwrite an existing file which is read only.

std::ofstream outputFile(OutputLocation, std::ios::binary);
outputFile.write((const char*)lpResLock, dwSizeRes);
outputFile.close();

Can anyone help us to mdify the code so that we are able to overwrite the existing file irrespective
of the file mode (read only, ... etc)

Thanks in advance.
Avatar of DanRollins
DanRollins
Flag of United States of America image

You can change the file permission settings before trying to write to the file:
       #include <sys/stat.h>
       #include <sys/stat.h>

        int nRet= _chmod( szPathAndNameOfTheFile, _S_IREAD | _S_IWRITE );
        if ( nRet != 0 ) {
                ... oops an error! ...
        }
Use SetFileAttributes API function before opening the file.
ASKER CERTIFIED SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of pbsmbc
pbsmbc

ASKER

Thanks Axter. Its working fine.
I have aquextion.Why FILE_ATTRIBUTE_ARCHIVE attribute is removing read only setting of the file?
>>Why FILE_ATTRIBUTE_ARCHIVE attribute is removing read only setting of the file?

It doesn't remove it.
When you call SetFileAttributes, you have to include all the attributes you want on the file.  If you don't include the attribute, than it gets removed.
Since the example code I posted only includes the FILE_ATTRIBUTE_ARCHIVE attribute, all other attributes will be removed.