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.
pbsmbcAsked:
Who is Participating?
 
AxterCommented:
SetFileAttributes(OutputLocation, FILE_ATTRIBUTE_ARCHIVE);

If you want to preserve the attributes, you can first read them, and save them for when you're done.
Example:

DWORD MyAttrib = GetFileAttributes(OutputLocation);
SetFileAttributes(OutputLocation, FILE_ATTRIBUTE_ARCHIVE);

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

SetFileAttributes(OutputLocation, MyAttrib); //Set it back to original value.
0
 
DanRollinsCommented:
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! ...
        }
0
 
AxterCommented:
Use SetFileAttributes API function before opening the file.
0
 
pbsmbcAuthor Commented:
Thanks Axter. Its working fine.
I have aquextion.Why FILE_ATTRIBUTE_ARCHIVE attribute is removing read only setting of the file?
0
 
AxterCommented:
>>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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.