2016-06-20 3 views
-1

C++을 사용하여 HTML 파일의 특정 문자열 (전체 줄이 아님)을 바꿀 수있는 방법을 찾고 있습니다. 나는 html 파일이있는 경우 예를 들어, 포함하는 : 나는 "밤"에 의해 "아침"을 교체해야하고,이 내입니다C++을 사용하여 텍스트 파일의 단어 바꾸기

</span><br><span class=text>night<br></span></td> 

:

</span><br><span class=text>morning<br></span></td> 

을 그리고 그것을 원하는대로 편집 코드 :

string strReplace = "morning"; 
    string strNew = "night"; 
    ifstream filein("old_file.html"); 
    ofstream fileout("new_file.html"); 
    string strTemp; 
    while(filein >> strTemp) 
    { 
    if(strTemp == strReplace){ 
     strTemp = strNew; 
    } 
    strTemp += "\n"; 
    fileout << strTemp; 
    } 

이 코드는 내 파일에 어떤 영향을 고려하지 않았고, 나는 이유는 대신 부분 문자열의 전체 라인을 변경에만 수 있다는 것이다 같아요. 누군가 나에게 올바른 구현을위한 제안을 할 수 있습니까? 미리 감사드립니다.

+0

filein >> 토큰을 읽습니다. 토큰은 공백으로 구분됩니다. 보십시오'종류 = 원본> 아침
'. –

+0

http://www.cplusplus.com/reference/string/string/getline/을 사용하여 파일을 한 줄씩 읽은 다음 http://www.cplusplus.com/reference/string/string/find/에서 하위 문자열을 찾으십시오. 그리고 찾으면 http://www.cplusplus.com/reference/string/string/replace/로 대체하십시오. – Marandil

답변

0

나는 원래의 질문을 읽어 방법에서를, 당신은, "밤"에 파일에 "아침"의 모든 인스턴스를 대체하기 위해 주어진에 단지 하나 개의 인스턴스가 필요합니다 선. 전체 파일을 문자열로 읽는 것으로 시작합니다.

std::string getfile(std::ifstream& is) { 
    std::string contents; 
    // Here is one way to read the whole file 
    for (char ch; is.get(ch); contents.push_back(ch)) {} 
} 

다음은 find_and_replace 기능합니다

void find_and_replace(std::string& file_contents, 
    const std::string& morn, const std::string& night) { 
    // This searches the file for the first occurence of the morn string. 
    auto pos = file_contents.find(morn); 
    while (pos != std::string::npos) { 
    file_contents.replace(pos, morn.length(), night); 
    // Continue searching from here. 
    pos = file_contents.find(morn, pos); 
    } 
} 

이어서

std::string contents = getfile(filein); 
find_and_replace(contents, "morning", "night"); 
fileout << contents; 

EDIT 주에서 : find_and_replace()가 CONST 자사 file_contents 문자열 매개 변수를 선언 할 것이다. 그냥 주목하고 고정.

+0

상세한 답변을 주셔서 대단히 감사합니다! – Saintycer

1

줄 전체를 가져 와서 부분 문자열을 검색하고 바꿀 수 있습니다. 이 방법, 당신도 전체 루프를 건너 뜁니다

std::string line; 

//Get line in 'filein' 
std::getline(filein, line); 

std::string replace = "morning"; 

//Find 'replace' 
std::size_t pos = line.find(replace); 

//If it found 'replace', replace it with "night" 
if (pos != std::string::npos) 
    line.replace(pos, replace.length(), "night"); 
+0

감사합니다! 그것은 문제를 완벽하게 해결했습니다. – Saintycer

0

여러 가지 방법으로 처리 할 수 ​​있습니다. 매우 일반적인 방법은 이전 문자열을 삭제하고 새 파일의 이름을 이전 파일 이름으로 변경하여 새 문자열로 파일을 만드는 것입니다.

그게 맞으면,이 콘솔 응용 프로그램을 방해 할 수 있습니다.


매개 변수 1

매개 변수 2 검색 할 문자열 것은, 내가 만들고있어

매개 변수 (3) 파일 경로 기본적으로


이다 사용할 수있는 대체 텍스트입니다 새 파일에 대한 일부 STD 스트림과 이전 파일에서 해당 문자열이있는 경우 해당 문자열을 찾은 경우 해당 문자열을 대체 한 다음 치환 발생 여부와 관계없이 결과를 파이프합니다 새 파일의 새 행으로 편집하십시오.

그런 다음 스트림을 닫고 파일 크기를 확인한 다음 비어 있지 않은 파일을 만드는 데 성공하면 이전 파일을 삭제하고 새 파일의 이름을 이전 파일 이름으로 변경합니다.

오류 코드 일명 errorlevel이 2 인 경우 입력 스트림이 작동하지 않는다는 의미입니다. 그것이 -1이면, 우리는 성공적으로 새로운 파일을 찾아서 대체하지 못했음을 의미합니다. 1 인 경우 올바른 매개 변수를 입력하지 않았 음을 의미합니다. 0 번 출구 만 성공을 나타냅니다.

이 기능을 사용하려면 예외 처리 및 더 강력한 파일 백업 솔루션을 추가해야합니다.

#include <iostream> 
#include <fstream> 
#include <string> 
#include <sys\stat.h> 

using namespace std; 

int main(int argc, char * argv[]) 
{ 
    if (argc != 4) { return 1; } 
    int exit_code = -1; 

    string textToFind = string(argv[1]); 
    string replacementText = string(argv[2]); 
    string fileToParse = string(argv[3]); 
    string fileToWrite = fileToParse+".rep"; 

    ifstream inputFileStream(fileToParse, ifstream::in); 
    if (!inputFileStream.good()) { return 2; } 

    ofstream outputFileStream(fileToWrite); 

    string fileLine; 
    while (getline(inputFileStream, fileLine)) 
    { 
     size_t substringPos = fileLine.find(textToFind); 
     if (substringPos != string::npos) 
     { 
      fileLine.replace(substringPos, textToFind.size(), replacementText); 
     }  
     outputFileStream << fileLine << '\n'; 
    } 
    outputFileStream.close(); 
    inputFileStream.close(); 

    struct stat st; 
    stat(fileToWrite.c_str(), &st); 
    int new_file_size = st.st_size; 

    if (new_file_size > 0) 
    { 
     if (remove(fileToParse.c_str())==0) 
     { 
      if (rename(fileToWrite.c_str(), fileToParse.c_str())==0) 
      { 
       exit_code = 0; 
      } 
     } 
    } 

    return exit_code; 
} 
관련 문제