파일 읽기/쓰기 & Regex - 정확히 일치하는 단어 찾기
C++/C++ 2021. 10. 1. 19:42 |텍스트 파일을 열어서 특정 단어가 있는 행을 지우기
#include <iostream>
#include <string>
#include <fstream>
#include <regex>
int main()
{
//파일 경로 입력 받기
std::cout << "편집할 파일의 경로를 입력하시오\n >> ";
string path;
std::cin >> path;
ENDL;
//파일 열기 시도
std::ifstream file;
file.open(path, ios::in);
if (file.is_open() == false) {
std::cout << "에러 - 잘못된 경로입니다." << std::endl;
return 0;
}
std::cout << path << " - 경로의 파일을 로드했습니다." << std::endl;
ENDL;
//삭제할 행에 포함되어야 할 단어 입력 받기
std::cout << "삭제하려는 행에 포함되어야할 단어를 입력하세요 \n >> ";
std::string wordToFind;
std::cin >> wordToFind;
ENDL;
//정규 표현식으로 찾을 단어 패턴 등록
std::regex exactWord("(^| )"+ wordToFind +"( |$)"); // regex : 앞뒤로 아무것도 붙지 않아야 함
std::string line;
std::string text;
int i = 1;
// 삭제할 행 찾기
while (std::getline(file, line))
{
if (std::regex_search(line,exactWord)) {
std::cout << i<<" 번째 줄이 해당 단어 """<<wordToFind<<"""를 포함하고 있습니다.\n : ";
std::cout << line << std::endl;
}
else {
text += line;
text.push_back('\n');
}
}
file.close();
//파일 쓰기 시도
std::ofstream newFile(path,ios_base::out);
if(newFile.is_open()==false) {
std::cout << "에러\n";
return 0;
}
newFile << text;
newFile.close();
std::cout << text;
}
'C++ > C++' 카테고리의 다른 글
Spin Lock 구현해보기 (0) | 2021.10.03 |
---|---|
volatile 키워드 (0) | 2021.10.03 |
가상 상속(virtual inheritance) (0) | 2021.08.28 |
friend 키워드 (0) | 2021.08.20 |
constexpr, consteval, constinit 키워드 & Static Initialization Order Fiasco (0) | 2021.07.14 |