我試圖打開一個文件,並修改其中的一些內容。我的第一個代碼看起來是這樣,C++ - 修改文件而不創建新文件
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char** argv) {
int status = 0;
//error if no filename
if(argc == 1) {
cerr << "No file specified. Please specify a filename" << endl;
status = 1;
}
//open a file and modify
for (int i = 1; i < argc; ++i) {
string line = "";
string filename = argv[i];
ifstream infile;
infile.open(filename);
if(infile.fail()) {
status = 1;
cerr << filename << ": No Such File Exist" << endl;
}
else{
while(getline(infile, line)) {
auto index1 = line.find('(');
auto index2 = line.find(')');
cout << index1 << " " << index2 << endl;
auto itor = line.begin();
if(index1 != string::npos) line[index1] = '[';
if(index2 != string::npos) line[index2] = ']';
}
infile.close();
}
}
return status;
}
我知道這是錯的直接修改line
因爲它不會更改文件的內容。有沒有一種方法可以直接修改文件?(無需創建新文件,並輸出line
)
@JoachimPileborg,因爲它只是將'('到'['和')'更改爲']''大小應該是相同的。 – Kevin217