複数の方法で対応できます。かなり一般的なのは、新しい文字列を含むファイルを作成し、古いファイルを削除して、新しいファイルを古いファイル名に名前変更することです。
これがあなたに合っていれば、このコンソールアプリケーションを邪魔することができます。
パラメータ1は
パラメータ2検索する文字列である
パラメータ3を使用するための置換テキストは、ファイルパス、基本的
です私が作ってるんです新しいファイルへのいくつかのSTDストリームと古いファイルから、問題の文字列があればそれを探し、そうであればその文字列を置き換えて、置換が発生しても結果をパイプする新しいファイルの新しい行として編集します。
次にストリームを閉じてファイルサイズを確認し、空でないファイルを作成できたら、古いファイルを削除して新しいファイルの名前を古いファイル名に変更します。
エラーコードが2の場合、入力ストリームが機能しないことを意味します。それが-1なら、つまり、新しいファイルを見つけたり、置き換えたりすることができなかったことを意味します。 1の場合は、正しいパラメータを指定しなかったことを意味します。ゼロ出口だけが成功を示します。
これを使用する場合は、例外処理と、おそらくより堅牢なファイルバックアップソリューションを追加する必要があります。
#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;
}
filein >>はトークンを読み込みます。トークンは空白で区切られます。 'class = text> morning
'を試してください。 –
http://www.cplusplus.com/reference/string/string/getline/でファイルを1行ずつ読み込み、http://www.cplusplus.com/reference/string/string/find/で部分文字列を探してください。見つけたら、http://www.cplusplus.com/reference/string/string/replace/に置き換えてください。 – Marandil