I am trying to remove the config.json file from program data, But with the below code it is showing "Permission Denied".
int main()
{
std::string f_strConfigFile = "C:\\ProgramData\\TestApplication\\TestConfig.json";
std::string l_strFileContents;
std::ifstream l_ifConfigFileStream(f_strConfigFile.c_str());
if (l_ifConfigFileStream)
{
l_ifConfigFileStream.seekg(0, ios::end);
size_t l_szFileSize = (size_t)l_ifConfigFileStream.tellg();
l_ifConfigFileStream.seekg(0, ios::beg);
char* l_chBuffer = new char[l_szFileSize 1];
memset(l_chBuffer, 0, l_szFileSize 1);
l_ifConfigFileStream.read(l_chBuffer, l_szFileSize 1);
l_strFileContents.assign(l_chBuffer);
delete[] l_chBuffer;
}
l_ifConfigFileStream.close();
if (l_strFileContents.empty())
{
l_strFileContents.assign("{}");
}
if (remove(f_strConfigFile.c_str()) != 0)
{
std::cout << "Failed to remove the file" << endl;
}
else
{
std::cout << "Removed the file" << endl;
}
return 0;
}
could any one suggest how to remove the config file?
CodePudding user response:
Common Application Data Folder
There might not be any issue with your code in itself. Although I stand by all the suggestions made in the comments. They will make your code more efficient.
In the comments you said:
I tried by printing errno. It is showing "Permission denied".
Administrator rights are needed to save files to the common application data folder (%programdata%). Whilst all users have read access.
If you want to delete, you would need elevated administrator rights.
Run your executable with elevation and I bet it will delete the file.
The principles of the above are also discussed here in one of the answers (How to write to the common Application Data folder?).
Administrator Rights
You also asked in the comments:
How to provide elevated permissions when removing the file from the code?
This is really a different question. For what it's worth, in my application I have a dedicated executable just for the administrative tasks. And I spawn it with elevated rights. The button on my dialog has a Shield to indicate it will need to run with elevation.
Of course you can right-click an executable and run with elevation. But programatically? If it is even possible? I would start a new question for that.
To address your original question, you need administrative rights to delete froms from that special folder.
