I'm trying to delete Windows Defender's scans history and backup history using C++, but I have no clue how I can do it.
I'm using this code:
std::string wdefenderhistory = "C:\\ProgramData\\Microsoft\\Windows Defender\\Scans\\History"; //defender history
std::string wdefenderbackupstore = "C:\\ProgramData\\Microsoft\\Windows Defender\\Scans\\BackupStore"; //defender backups
if (std::filesystem::exists(wdefenderhistory)) {
std::filesystem::remove_all(wdefenderhistory);
}
if (std::filesystem::exists(wdefenderbackupstore)) {
std::filesystem::remove_all(wdefenderbackupstore);
}
I tried already with std::fs::remove() and std::remove(), but nothing works.
Any way to force deleting a folder with admin rights without using system() / ShellExecute() syntax?
Started the program as admin, etc etc - nothing works, so I'm asking there.
std::fs::remove_all() is also giving me a memory error:
I'm sure for 99% that error code will be 0x5
I noticed that some folders in directory (only CacheManager and everything under it needs) does not needs the "admin" perms,
so i solved the problem with:
code is deleting every folder w/o admin privilege and keeps C:\..\History path :)
std::string wdefenderhistory = "C:\\ProgramData\\Microsoft\\Windows Defender\\Scans\\History"; //defender history
std::string wdefenderbackupstore = "C:\\ProgramData\\Microsoft\\Windows Defender\\Scans\\BackupStore"; //defender backups
if (std::filesystem::exists(wdefenderhistory)) {
const std::filesystem::path defenderhist{ "C:\\ProgramData\\Microsoft\\Windows Defender\\Scans\\History" };
for (auto const& dir_entry : std::filesystem::recursive_directory_iterator{ defenderhist })
{
try {
const std::filesystem::path cachemanager{ "C:\\ProgramData\\Microsoft\\Windows Defender\\Scans\\History\\CacheManager" };
for (auto const& dir_entryy : std::filesystem::recursive_directory_iterator{ cachemanager })
{
if (dir_entry != dir_entryy && dir_entry != cachemanager) {
std::filesystem::remove_all(dir_entry);
}
}
}
catch (std::filesystem::filesystem_error const& ex) {
std::cout
<< "what(): " << ex.what() << '\n'
<< "path1(): " << ex.path1() << '\n'
<< "path2(): " << ex.path2() << '\n'
<< "code().value(): " << ex.code().value() << '\n'
<< "code().message(): " << ex.code().message() << '\n'
<< "code().category(): " << ex.code().category().name() << '\n';
}
}
}
Please mark this thread as solved because i dont know how to do it, thank you
Related
I am trying to stream the data in the retrieved s3 file into a local file on disk. However, when I try my current code, I do not get a file stored on my computer, or in any location near the code.
I first request the object from s3 using a getObjectOutcome. After success, I want to create an ofstream and redirect the objects stream buffer to my local object so that I can create a file on disc. However, the following code does not create a file on my computer. What am I doing wrong?
Here is the get object function:
bool GetObject(const Aws::String& objectKey,
const Aws::String& fromBucket,
const Aws::Client::ClientConfiguration& clientConfig) {
Aws::S3::S3Client client(clientConfig);
Aws::S3::Model::GetObjectRequest request;
request.SetBucket(fromBucket);
request.SetKey(objectKey);
Aws::S3::Model::GetObjectOutcome outcome =
client.GetObject(request);
if (!outcome.IsSuccess()) {
const Aws::S3::S3Error& err = outcome.GetError();
std::cerr << "Error: GetObject: " <<
err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
}
else {
std::cout << "Successfully retrieved '" << objectKey << "' from '"
<< fromBucket << "'." << std::endl;
std::ofstream localfile;
localfile.open(objectKey.c_str(), std::ios::out | std::ios::binary);
auto retrieved = outcome.GetResult().GetBody().rdbuf();
localfile << retrieved;
std::cout << "Done!";
}
return outcome.IsSuccess();
}
Here is an image of the memory for local file and retrieved:
Would someone teach me what I am doing this wrong, or how to correctly download data from s3 to disc?
Thanks.
I tried downloading some data from s3 to disc. I am having trouble outputting this data via stream buffer to local file. I have been looking online and cannot find a similar problem.
Update:
I am now on my second day of trying to figure this out to no avail. For some reason, the code will not even output a file after it has been created to the directory I have set up for the .nc files to be written to.
I have tried the following updates:
bool GetObject(const Aws::String& objectKey,
const Aws::String& fromBucket,
const Aws::Client::ClientConfiguration& clientConfig) {
Aws::S3::S3Client client(clientConfig);
Aws::S3::Model::GetObjectRequest request;
request.SetBucket(fromBucket);
request.SetKey(objectKey);
Aws::S3::Model::GetObjectOutcome outcome =
client.GetObject(request);
if (!outcome.IsSuccess()) {
const Aws::S3::S3Error& err = outcome.GetError();
std::cerr << "Error: GetObject: " <<
err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
}
else {
std::cout << "Successfully retrieved '" << objectKey << "' from '"
<< fromBucket << "'." << std::endl;
//create the filename, which will be the objectKey
std::string local_file_name = "./netcdf/" + objectKey;
std::ofstream local_file(local_file_name, std::ios::binary);
auto &retrieved = outcome.GetResult().GetBody();
local_file << retrieved.rdbuf();
std::cout << "Done!";
}
return outcome.IsSuccess();
}
Then, after opening the ./netcdf folder, there is no output.
Here is the file structure inside my project for reference with the code:
I am still confused as to what I need to do here.
Thank you for all of the help you can offer!
You are using a folder with "./" at the front. This means that the file will be relative to the current working directory (cwd) of the binary. That is likely not the src folder
Just to get past your problem, use a full absolute path to see if the rest of your code works.
Also, try adding
// You need "#include <filesystem>" for the next line
cout << std::filesystem::current_path();
To see where the files you made might be
I am using a boost::shared_ptr to point to a plugin class. Plugin is a map <string, shared_ptr>. The first time I find a certain plugin in the map, it works fine. However, any subsequent time I try to find a particular plugin, I get a SIGSEGV error. When stepping through my code, I get to foundPlugin = a->second->onCommand(command);and find that a->second is not accessible anymore. This error only happens when I am running in Linux, however. I have no issues while running in Windows. Is there some sort of issue with boost::shared_ptr and linux? I have tried using std::shared_ptr, but I have to use a boost::dll::import function that returns a boost::shared_ptr, and I haven't found an alternative for that yet. Any insight is greatly appreciated!
I load plugins like this:
bool PluginManager::loadPlugin(std::string pluginPath, std::string
pluginName, std::string pluginType)
{
bool couldLoad = false;
boost::filesystem::path libPath = boost::filesystem::current_path();
boost::shared_ptr<my_plugin_api> plugin;
std::cout << "Loading the plugin " << pluginName << std::endl;
if (pluginName == "")
{
pluginName = "plugName";
}
try
{
plugin = boost::dll::import<my_plugin_api>(
libPath / pluginName,
pluginType,
dll::load_mode::append_decorations
);
Plugin.insert(std::pair<std::string,boost::shared_ptr<my_plugin_api>>
(pluginName, plugin));
std::cout << "Loading the plugin " << pluginName << " (SUCCESS)" <<
std::endl;
couldLoad = true;
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return couldLoad;
}
After much more testing, I feel like my problems are in the above section of code. the boost::dll::import function acts as if it finds a .so, but does not return anything in the boost::shared_ptr, which in turn causes the second snippet of code to fail. Any ideas of why this boost::dll::import function might be acting weirdly in Linux?
bool PluginManager::onCommand(const char* command, const char* pluginName)
{
bool foundPlugin = false;
auto a = Plugin.find(pluginName);
if (a == Plugin.end())
{
std::cerr << "plugin " << pluginName << " not found" << std::endl;
}
else
{
foundPlugin = a->second->onCommand(command);
}
return foundPlugin;
}
please help me ....
I want to show & return path of some of my files .
But unfortunately it does not return the path of all files ,
Please see the photo below
my code :
const std::filesystem::directory_options options = (
std::filesystem::directory_options::follow_directory_symlink |
std::filesystem::directory_options::skip_permission_denied
);
try
{
for (const auto& dirEntry :
std::filesystem::recursive_directory_iterator("C:\\",
std::filesystem::directory_options(options)))
{
std::cout << dirEntry.path().u8string() << std::endl;
}
}
catch (std::filesystem::filesystem_error & fse)
{
std::cout << fse.what() << std::endl;
}
error :
status: The process cannot access the file because it is being used by another process.: "C:\pagefile.sys"
what is the problem?
How do I reject this error?
I solved it this way:
if (!strstr(dirEntry.path().filename().u8string().c_str(), ".sys"))
{
std::cout << dirEntry.path().u8string() << std::endl;
}
I'm using visual studio 2017, running with the c++17 ISO Standard(not boost) set to be able to use <filesystem>. I'm running into a wall though because everytime I run, whether in debug or release, file_copy() gives me the error access denied. I've checked the other bits of my code and the only thing that isn't working is file_copy(). Does anyone know why I'm getting this error and how to fix it? I'm the administrative account on my PC.
std::vector<std::string> findAndCopyFiles()
{
std::vector<std::string> fileNames;
std::error_code errCode;
errCode.clear();
fs::current_path("C:\\Users\\kenny\\Desktop\\Engine", errCode);
std::cout << errCode.message() << std::endl; errCode.clear();
fs::path pa = fs::current_path();
pa += "\\TEMP";
std::cout << pa.string() << std::endl;
if (fs::create_directory(pa, errCode))//Create directory for copying all files)
{
std::cout << "Directory created successfully" << std::endl;
std::cout << errCode.message() << std::endl; errCode.clear();
}
fs::path tempDir(pa);
fs::path currentDirectory = fs::current_path();
fs::recursive_directory_iterator dirIter(currentDirectory);
for (auto &p : dirIter)
{
if (p.path().extension() == ".cpp" || p.path().extension() == ".h")
{
//std::string fileContents = getFileContents(p.path().string());
std::string fileName = p.path().stem().string();
if (!fs::copy_file(p.path(), tempDir, fs::copy_options::overwrite_existing, errCode))
{
std::cout << "failed to copy file: " << fileName << " from " << p.path().string() << " to " << tempDir.string() <<std::endl;
}
std::cout << errCode.message() << std::endl; errCode.clear();
//ensures file is a cpp file before adding it to list of fileNames
if (p.path().extension().string() == ".cpp")
{
auto it = std::find(fileNames.begin(), fileNames.end(), fileName); //seaches TEMP folder for file
if (it == fileNames.end())
{//if file was not found in vector of registered file names, add it
fileNames.push_back(fileName);
}
}
}
}
std::cout << "All files found. " << fileNames.size() << " files were found" << std::endl;
return fileNames;
}
As per the comments. You were trying to overwrite a directory with a regular file. From the documentation [trimmed]
o Otherwise, if the destination file already exists...
o Report an error if any of the following is true:
o to and from are the same as determined by equivalent(from, to);
o to is not a regular file as determined by !is_regular_file(to)
So you need to append the filename to the destination directory path using the `std::filesystem::operator/ overload (untested)...
if (!fs::copy_file(p.path(), tempDir / p.filename(), fs::copy_options::overwrite_existing, errCode))
Below is a simple class which attempts to write an integer to a file. The mode of writing the file is to append characters at the end of the file (In this mode, file should be created if it doesn't exist)
#include <iostream>
#include <fstream>
class TestFileStream
{
private:
std::ofstream* _myFileStream;
bool isFileOpen;
public:
TestFileStream():isFileOpen(false)
{
_myFileStream = new std::ofstream("TestFile.txt", std::ios_base::out | std::ios_base::app );
isFileOpen = _myFileStream->is_open();
if( !isFileOpen )
{
std::cout << "Unable to open log file" << std::endl;
std::cout << "Good State: " << _myFileStream->good() <<std::endl;
std::cout << "Eof State: " << _myFileStream->eof() <<std::endl;
std::cout << "Fail State: " << _myFileStream->fail() <<std::endl;
std::cout << "Bad State: " << _myFileStream->bad() <<std::endl;
}
else
{
std::cout << "Opened log file" << std::endl;
}
}
~TestFileStream()
{
_myFileStream->close();
delete _myFileStream;
_myFileStream = nullptr;
}
void WriteFile( unsigned number )
{
if ( isFileOpen )
{
(*_myFileStream) << "Number: " << number << std::endl;
}
}
};
int main()
{
// Number of iterations can be multiple.
// For testing purpose, only 1 loop iteration executes
for( unsigned iter = 1; iter != 2; ++iter )
{
TestFileStream fileWriteObj;
fileWriteObj.WriteFile( 100+iter );
}
return 0;
}
When I execute the above code, I get following log output:
Unable to open log file
Good State: 0
Eof State: 0
Fail State: 1
Bad State: 0
This seems like trivial task, but I am not able to find out whats causing the failure. Note that this question is most likely related to the following question
Just to summarize the comments, there is nothing wrong about the code you posted (apart from the rather unconventional new ostream ;) )
Note however that opening files may fail for a number of reasons (Permissions, file in use, disk unavailable, the file does not exist, the file exists...). That is why you must always test it.
If you tried to run the above code in an online emulator, then chances are file IO is disabled. Which would explain why you get that the streams fail-bit is set.