Check if a file has a certain string in its name C++ - c++

I'm programming a tool in C++ to remove the 000.exe malware. The malware creates a lot of files on the desktop named "UR NEXT UR NEXT UR NEXT" etc. My first step is to remove all these files from the desktop. What can I do to check every file on the desktop and for each one that contains the string "UR NEXT" somewhere in the file name, delete it. I have a basic structure of my program already written but I'm really stuck figuring out the user's username folder, then deleting ever file containing "UR NEXT" on the desktop. Any help would be greatly appreciated. I'm using Visual Studio 2019 and I already have an elevation added to the program.
#include <iostream>
#include <Windows.h>
#include <WinUser.h>
using namespace std;
int main()
{
string answer;
cout << "=~=~=~=~=~=~=~=~=~=~=~=~=~=\n000.exe Removal Tool\n\nby OrcaTech\n\nThis tool can be used to remove the 000.exe malware from your Windows PC. Type \"y\" below and press [ENTER] to begin the removal process.\n=~=~=~=~=~=~=~=~=~=~=~=~=~=" << endl;
cin >> answer;
if (answer == "y")
{
cout << "Starting Removal Process..." << endl;
cout << "Your computer will restart multiple times." << endl;
//Stop "run away" spam message boxes
system("taskkill /f /im runaway.exe");
//Change the wallpaper back to the default.
const wchar_t* path = L"%SystemRoot%\\Web\\Wallpaper\\Windows\\img0.jpg";
SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (void*)path, SPIF_UPDATEINIFILE);
/* code to delete all files on desktop containing UR NEXT goes here */
system("pause");
return 0;
} else {
exit(0);
}
}

You can use std::filesystem::directory_iterator to iterate over every file in the desktop folder and remove the files with specific names:
#include <filesystem>
#include <string>
#include <vector>
int main()
{
std::vector<std::filesystem::path> filesToRemove;
for (const auto& i : std::filesystem::directory_iterator("path_to_desktop"))
{
std::string fileName = i.path().filename().string();
if (fileName.find("UR NEXT") != std::string::npos)
{
filesToRemove.emplace_back(i);
}
}
for (const auto& i : filesToRemove)
{
std::filesystem::remove(i);
}
}

Related

How to navigate through directories using c++ to create a file explorer

I'm trying to create a file explorer in C++ using Ncurses for my class. Currently I'm trying to find a way to navigate through the file system and find out if 'x' is file/directory and act accordingly.
The problem is I can't find a way to navigate through directories they way I'd like. For example, in the code below I start at "." and then read it while saving some info of said directory and its files. But I'd like to define the cwd to "/home" everytime the program runs and then go from there exploring whatever the user wants like:
display /home -> user selects /folder1 -> display /folder1 -> user selects /documents -> ...
I've read about scripts and tried to create a "cd /home" script but it doesn't work. Somewhere I read that the execve() function might work, but I don't understand it. I've got a feeling that I'm overthinking this, and frankly I'm stuck.
edit: In essence I'd like to find: How to make it so that my program starts at "path" so that when I call getcwd() it returns "path" and not the actual path of the program.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>
#include <linux/limits.h>
#include <iostream>
#include "contenido.cpp"
using namespace std;
//Inicia main
int main(int argc, char const *argv[]) {
DIR *dir; //dir is directory to open
struct dirent *sd;
struct stat buf; //buf will give us stat() atributes from 'x' file.
char currentpath[FILENAME_MAX]; //currentpath
contenido dcont;
//system (". /home/rodrigo/Documentos/Atom/Ncurses/Proyecto/beta/prueba.sh");
if((dir = opendir(".")) == NULL){ /*Opens directory*/
return errno;
}
if(getcwd(currentpath, FILENAME_MAX) == NULL){
return errno;
}
while ((sd= readdir(dir)) != NULL){ /*starts directory stream*/
if(strcmp(sd -> d_name,".")==0 || strcmp(sd -> d_name,"..") ==0){
continue;
}
//Gets cwd, then adds /filename to it and sends it to a linked list 'dcont'. Resets currentpath to cwd
//afterwards.
getcwd(currentpath, FILENAME_MAX);
strcat(currentpath, "/");
strcat(currentpath, sd->d_name);
string prueba(currentpath);
//std::cout << currentpath << '\n';
dcont.crearnodo(prueba);
if(stat(currentpath, &buf) == -1){
cout << currentpath << "\n";
perror("hey");
return errno;
}
getcwd(currentpath, FILENAME_MAX);
//Prints Files and Directories. If Directory prints "it's directory", else prints "file info".
if (S_ISDIR(buf.st_mode)) {
cout << sd->d_name << "\n";
cout << "ES DIRECTORIO\n";
}else
cout << sd->d_name << "\n";
cout <<"Su tamaƱo es: " << (int)buf.st_size << "\n";
//system("ls");
}
closedir(dir);
dcont.mostrardircont(); //prints contents of the linked list (position in list and path of file).
return 0;
}
To change your current working directory use chdir
If you want to change your cwd to "/home"
chdir("/home");
The chdir only persists within the program that did it (or subprocesses). It won't cause the shell to change. There's an application (wcd) which does something like what you're trying, which combines the navigation with a shell script.

Whenever I try to run my project in codelite, any changes I've made seem to be ignored

An example of my situation would be when I add a cout in main and when I build and run the program that cout is never displayed (it's the second line of code so I don't believe the issue has anything to do with the code).
I should also mention that I didn't make this project, a group member did. So I had to create a workspace and add the existing project file that way. Other than the issue I've specified, everything else works like a charm.
Some of the things I've tried include building, rebuilding, stopping and resuming the build, closing and reopening the workspace, closing and reopening the program, making a new workspace, rebuilding the project, reloading the workspace, rebuilding the workspace, and cleaning the workspace. None of these worked. I have no idea what else to do.
There are a lot of classes and header files, so it'd take me awhile to add all of them in here but for now I'll give you main:
#include <iostream>
#include "Functions.h"
#include "Charge.h"
#include "Grid.h"
#include "Property.h"
using namespace std;
int main()
{
cout << "Welcome to the world of Monopoly\n";
cout << endl << "I can work!"; # This is the cout that I added and was ignored.
//Get the number of players
int numberOfPlayer;
setNumberOfPlayer(numberOfPlayer);
//Get the name of each player
Player *players = new Player[numberOfPlayer];
setNameOfPlayer(players, numberOfPlayer);
//Initialize the map
cout << "Loading...";
//Current map size is 10 grids
int mapSize = 10;
Grid *grids[mapSize];
initializeGrids(grids, mapSize);
//progress is used to record a player's position and whether the player is bankrupt
Progress *progress = new Progress[numberOfPlayer];
initializeProgress(progress, numberOfPlayer);
cout << "Complete\n\n";
//Start a round. Iteration will continue if the game is not over.
//Game is over when only one player is not bankrupt
int round = 0;
bool gameOver = false;
while (!gameOver) {
gameOver = roundStart(round, players, numberOfPlayer, grids, mapSize, progress);
round++;
}
//Print out the winner
printWinner(players, numberOfPlayer, progress);
return 0;
}
statement : cout << endl << "I can work!"; works good, it output your string. Ok, you can try cout<< " \n I can work!";.
The order problem , try
cout << "I can work!" << endl;

Opening up Microsoft Word in my C++ program

As the title mentions, I am trying to open Microsoft Word through this program and am running into a little bit of difficulty. Having done some research into processes, I decided to go through the route of working with Process ID's and the Fork function to handle opening another file within my program. The area where I seem to be running into some difficulty are with the exec family functions. Their seems to be a variety of different uses for these functions, but I am having a difficult time wrapping my head around which function I should use and whether I am syntatically laying out my arguments correctly.
My console prints the following out to the screen when I type "msword":
Hello ---, what application would you like to open?
msword
Creating Child Process To Open Microsoft Word
parent process
Opening Microsoft Word
#include <stdio.h>
#include <iostream>
#include <string>
// Routine Headers
#include <sys/types.h>
#include <unistd.h>
using namespace std;
//function that actually processes loading the program, will take the result of searchApplication
void loadApplication(string path)
{
// If the user typs Microsoft Word (msword abbreviation...)
if(path == "msword")
{
cout << "Creating Child Process To Open Microsoft Word\n";
pid_t ProcessID = fork();
if(ProcessID == -1)
{
cout << "Error creating another Process... Exiting\n";
exit(1);
}
// This is the child process
else if (ProcessID == 0)
{
execle("/Applications/Microsoft Office 2011", nullptr);
}
// This is the parent process
else
{
cout << "parent process\n";
}
}
int main()
{
cout << "Hello ---, what application would you like to open?\n";
string input;
cin >> input;
loadApplication(input);
return 0;
}
You don't have to use fork/exec for this. Just pass the open command to system():
#include <cstdlib>
int main() {
system("open /Applications/App\\ Store.app");
return 0;
}
Note that you will need to escape any spaces in the application name (as shown above), and specify the full name (not just the displayed name).
Here's a very closely related question.

Ifstream file does not open although everything seems in place (c++)

I'm trying to write a program to parse the first and sixteenth columns of a CSV file (converted into .txt). I have the CSV ("posts.txt") document in the folder with the executable. But, whenever I try to run the executable, my program delivers that it cannot open the file (or that "!infile.is_open()"). Mind giving me some assistance? I'm running in Xcode 3.2.3 on Mac OSX 10.8.3. The code is shows below.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string.h>
using namespace std;
void answeredPostGrabber()
{
ifstream inFile("posts.txt");
string postNumber;
string answerNumber;
string throwAway;
if(inFile.is_open())
{
while(inFile.good())
{
getline(inFile,postNumber,',');
cout << postNumber << ",";
for(int y=1;y++;y<16)
{
getline(inFile,throwAway,',');
}
getline(inFile,answerNumber,',');
cout << answerNumber << endl;
ofstream edges;
edges.open("edges.txt",ios::app);
edges << postNumber << "," << answerNumber<< endl;
edges.close();
ofstream nodes;
nodes.open("nodes.txt",ios::app);
nodes << postNumber << "\n" << answerNumber << endl;
nodes.close();
getline(inFile,throwAway);
}
}else cout << "ERROR: Unable to open file." << endl;
}
int main ()
{
answeredPostGrabber();
return 0;
}
Thank you in advance!
I have the CSV ("posts.txt") document in the folder with the executable.
The file should be present in the current working directory of your process, which may or may not be the same directory where the executable lives. If in doubt, try specifying the full path in ifstream inFile(...); to see whether that changes things.
Additionally, the file needs to have the correct permissions to ensure that it's readable by the process.

C++ Trouble Reading a Text File

I'm trying to read a text file but nothing is coming out. I feel like maybe It's not linking correctly in my Visual Studio Resources folder but if I double click it - it opens fine in visual studio and it doesn't run into any problems if I test to see if it opens or if it is good. The program compiles fine right now but there's not output. Nothing prints to my command prompt. Any suggestions?
Code
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
char str[100];
ifstream test;
test.open("test.txt");
while(test.getline(str, 100, '#'))
{
cout << str << endl;
}
test.close();
return 0;
}
Text File
This is a test Textfile#Read more lines here#and here
You try to open file by name without path, this means the file shall be in current working directory of your program.
The problem is with current directory when you run your program from VS IDE. VS by default sets current working directory for runnning program to project directory $(ProjectDir). But your test file resides in resources directory. So open() function could not find it and getline() immediately fails.
Solution is simple - copy your test file to project directory. Or copy it to target directory (where your program .exe file is created, typically $(ProjectDir)\Debug or $(ProjectDir)\Release) and change working directory setting in VS IDE: Project->Properties->Debugging->Working Directory, set to $(TargetDir). In this case it will work both from IDE and command line/Windows Explorer.
Another possible solution - set correct path to file in your open() call. For testing/education purposes you could hardcode it, but actually this is not good style of software development.
Not sure if this will help but I wanted to simply open a text file for output and then read it back in. Visual Studio (2012) seems to make this difficult. My solution is demonstrated below:
#include <iostream>
#include <fstream>
using namespace std;
string getFilePath(const string& fileName) {
string path = __FILE__; //gets source code path, include file name
path = path.substr(0, 1 + path.find_last_of('\\')); //removes file name
path += fileName; //adds input file to path
path = "\\" + path;
return path;
}
void writeFile(const string& path) {
ofstream os{ path };
if (!os) cout << "file create error" << endl;
for (int i = 0; i < 15; ++i) {
os << i << endl;
}
os.close();
}
void readFile(const string& path) {
ifstream is{ path };
if (!is) cout << "file open error" << endl;
int val = -1;
while (is >> val) {
cout << val << endl;
}
is.close();
}
int main(int argc, char* argv[]) {
string path = getFilePath("file.txt");
cout << "Writing file..." << endl;
writeFile(path);
cout << "Reading file..." << endl;
readFile(path);
return 0;
}