How to find words in all files inside a folder?

How to make a code which can find specific words in all files of the folder and delete files without these specific words. I have a code which finds a word in only 1 text file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// ConsoleApplication1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include "pch.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{

	ifstream input;
	size_t pos;
	string line;

	input.open("t.txt");
	if (input.is_open())
	{
		while (getline(input, line))
		{
			pos = line.find("hey");
			if (pos != string::npos) // string::npos is returned if string is not found
			{
				cout << "Found!";
				break;
			}
		}
	}

	system("pause");
}
Last edited on
As a design, that's a dangerous tool. One slip of the command and you can delete everything.

I'd highly suggest you reconsider for a version that is reversible. Say, move all the files to another directory, which could easily be deleted once it is verified the find was correct.

That said, this is OS specific, but if you're willing to use the new std Filesystem features in C++17, you have tools for recursive or single directory searching for files, which is then portable to most operating systems.

If you can use Boost, the very same Filesystem is available for older C++ standards.

There is a directory iterator, which would allow you to sequence through the files.



Topic archived. No new replies allowed.