私はコマンドラインプログラムを書いて、行ごとに新しいターゲットファイルにパイプすることによって、アーカイブされたサーバログをきれいにし、再編成する必要があります。各ターゲットファイルにはregExフィルタ項目があります。したがって、ソースファイルから赤色の行がregExと一致する場合、この特定のターゲットファイルに書き込まれます。C++ ofstream - ファイルに1文字列だけが書き込まれ、前の文字列が上書きされます。なぜですか?
設定ファイルからregEx文字列とそのターゲットファイル文字列を読み込み、これらの情報をベクトルに保存して、設定から赤色の新しいタグセット/フィルタのペアが1つずつ動的にサイズ変更できるようにします。
次のコードは、すべてのソースファイルをループする方法を示しています。各行について、1行ずつ読み込み、赤色になる可能性のあるすべての行について、設定で定義されているすべてのフィルタを繰り返します。 regExは私がこの行をofstreamに書き込む行と一致します。私がこれを行うたびにofstreamは新しいターゲットファイルを開く前にclose()dとclear()edを取得します。
私の問題は、プログラムの終了後にターゲットファイルに1つの文字列しか含まれていない限り、すべて正常に動作するということです。それはファイルに書き込んだ最後の文字列を含んでいます。
以前にファイルに書き込んだ文字列はすべて上書きされているようです。私は何か間違っていると思っていますが、私はそれが何であるかは分かりません。
ここでは、コードの抜粋です:
void StringDirector::redirect_all() {
ifstream input; //Input Filestream init
ofstream output; //Output Filestream init
string transfer; //Transfer string init
//regex e;
for (unsigned k = 0; k<StringDirector::v_sources_list.size(); k++) { //loop through all sources in v_sources_list vector
cout << endl << " LOOP through sources! Cycle #" << k << "/string is: " << StringDirector::v_sources_list[k] << endl;
input.close(); //close all open input files
input.clear(); //flush
input.open(StringDirector::v_sources_list[k].c_str()); //open v_sources_list[k] with input Filestream
if (!input) {
std::cout << "\nError, File not found: " << StringDirector::v_sources_list[k] << "\nExiting!"; //Throw error if file cannot be opened
exit(1);
}
cout << endl << " " << StringDirector::v_sources_list[k] << " opened" << endl;
getline(input, transfer); //get a first line from input Filestream and write to transfer string
while (input) { //do that as long as there is input
for (unsigned j = 0; j<StringDirector::v_filters_list.size(); j++) { //loop through all filters in v_filters_list vectord
cout << endl << " LOOP through filters! Cycle #" << j << "/string is: " << StringDirector::v_filters_list[j] << endl;
regex e(StringDirector::v_filters_list[j]);
if (regex_search(transfer, e)) {
reopen(output, StringDirector::v_targets_list[j].c_str());
output << transfer << endl;
cout << endl << " -- MATCH! Writing line to: " << StringDirector::v_targets_list[j] << endl ;
}
}
getline(input, transfer);
if (input)cout << endl << "+ got another line: " << transfer << endl;
else cout << endl << "End Of File!" << endl;
}
}
}
はEDIT:
私は、私はそれがすると思い、あなたのファイルのオープンモード "を追加" してください私は
template <typename Stream>
void reopen(Stream& pStream, const char * pFile,
std::ios_base::openmode pMode = ios_base::out)
{
pStream.close();
pStream.clear();
pStream.open(pFile, pMode);
}
ありがとう!今それは素晴らしい仕事です! –