[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 239
  • Last Modified:

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.
0
pbsmbc
Asked:
pbsmbc
  • 3
1 Solution
 
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
 
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
 
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

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now