|
카르본 님이 쓰신 글 :
: 파일내 문자변경하는 플그램을 짜고 있는데요..
: 궁금한게 있습니다~
: (ansi c++로 짜고 있는데요..)
:
: 에디트 하려면..
:
: 1. 파일읽기
: 2. 파일내 특정문자열 검색
: 3. 위치 포인터 산출
: 4. 입력
: 5. 입력된 값 파일에 쓰기(이때 산출된 포인터의 범위만큼만 쓰기)
:
: 이렇게 할라구 하는데..-.-;
: 3번이 좀 문제여서요..
: 메모리에 파일을 모두 올리고 쓸수도 없구요..
: 어떻게 해야할지..ㅜ.ㅜ
:
: 어떤함수를 써야 위치포인터를 알며, 파일에 쓸때 또 어떻게 써야 범위만큼만 쓸 수 있을지..
:
: 아시는 분은 시원한 답변부탁드림돠...꾸벅~~
파일에 있는 특정 문자열을 검색해서 다른 문자열로 치환한다고 하면,
한 라인씩 읽어서 바꾸면 되지 않나요?
그럼 다음 코드처럼 구현하면 간단할텐데요.
//---------------------------------------------------------------------------
#include <cstdlib>
#include <iostream>
#include <fstream>
#pragma hdrstop
#include <string>
//---------------------------------------------------------------------------
#pragma argsused
using namespace std;
template<typename string_type>
string_type string_replace(const string_type& s, const string_type& old_pattern,
const string_type& new_pattern, bool replace_all = true);
int main(int argc, char* argv[])
{
if (argc < 4) {
cerr << "Usage: " << argv[0]
<< " input_file output_file old_pattern new_pattern\n";
exit(0);
}
ifstream fin(argv[1]);
ofstream fout(argv[2]);
string old_pattern(argv[3]);
string new_pattern(argv[4]);
string sLine, sReplacedLine;
while(1) {
getline(fin, sLine);
if (!fin.good()) break;
sReplacedLine = string_replace(sLine, old_pattern, new_pattern);
fout.write(sReplacedLine.c_str(), sReplacedLine.length()) << '\n';
}
return 0;
}
//---------------------------------------------------------------------------
template<typename string_type>
string_type string_replace(const string_type& s, const string_type& old_pattern,
const string_type& new_pattern, bool replace_all)
{
if (s.size() < old_pattern.length()) return s;
string_type sReplaced = s;
size_t pos = s.find(old_pattern, 0);
if (pos != string::npos) {
sReplaced = s.substr(0, pos) + new_pattern
+ s.substr(pos + old_pattern.length(), s.length());
if (replace_all)
while (1) {
pos = sReplaced.find(old_pattern, pos + new_pattern.length());
if (pos == string::npos) break;
sReplaced = sReplaced.substr(0, pos) + new_pattern
+ sReplaced.substr(pos + old_pattern.length(), s.length());
}
}
return sReplaced;
}
|