[c++] 파일 내용 검색
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt");
std::string line;
if (file.is_open()) {
while (getline(file, line)) {
if (line.find("target_string") != std::string::npos) {
std::cout << "String found in file: " << line << std::endl;
// 원하는 작업을 수행합니다. 예를 들어, 찾은 문자열을 가공하거나 해당 줄을 파일에 쓸 수 있습니다.
}
}
file.close();
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
위 코드는 example.txt
파일에서 “target_string”이라는 문자열을 찾아서 해당 라인을 출력하는 간단한 예시입니다. 변수나 오류 처리를 추가하여 실제 프로젝트에 사용할 수 있는 완성된 코드를 작성할 수 있습니다.
이 코드는 파일을 열고 각 라인을 읽어들여 해당 문자열이 있는지 검사한 후, 원하는 작업을 수행하게 됩니다. 이를 응용하여 파일 내용을 검색하고 관련된 작업을 수행하는 더 복잡한 프로그램을 작성할 수 있습니다.
참고 문헌:
- C++ 파일 처리: https://www.learncpp.com/cpp-tutorial/186-basic-file-io/
- C++ string 클래스: https://www.cplusplus.com/reference/string/string/