Chris White Chris White - 2 months ago 18
C++ Question

C++ Feeding strings from a text document as arguments

Is there a way to feed strings from a text document directly as arguments? Preferably without saving them?

I have a killProcessByName method that is expecting an argument so I was wondering if it is possible to read the first line from my text document, copy it then send it as an argument? Then move on to the next line, preform the same thing and repeat the process until there are no words left in the document?

Example of my list:

Apples.exe
Blueberries.exe
Watermelon.exe
Oranges.exe
...


The method I'm targeting

void killProcessByName(const char *filename)
{
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof (pEntry);
BOOL hRes = Process32First(hSnapShot, &pEntry);
while (hRes)
{
if (strcasecmp(pEntry.szExeFile, filename) == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
(DWORD) pEntry.th32ProcessID);
if (hProcess != NULL)
{
TerminateProcess(hProcess, 9);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}

Answer
#include <iostream> // std::cout, std::endl
#include <fstream>  // std::ifstream
using namespace std;
int main()
{
    // open your file
    ifstream input_file("test.txt");

    // create variables
    string name;

    // while there are entries
    while(input_file >> name)
    {
        killProcessByName(name.c_str());
    }

   // close the file
   input_file.close();

   return 0;
}