0. 基礎知識 - ファイルの読み書きのための fstream ファイルストリーム
#include <fstream>
using namespace std;
fstream myfile("Information.txt");
if (!myfile.is_open())
{
cout << "can not open this file" << endl;
return 0;
}
while(!myfile.eof())
- ファイルの内容を temp に読み取り、一行ずつ出力します。
#include <string>
string temp;
while(!myfile.eof()){
getline(myfile,temp);
cout<<temp;
}
myfile.seekp(-3,ios::cur);
myfile.seekg(-3,ios::cur);
myfile.close();
1. タスク
- 実行するたびに txt の内容を変更するプログラムを作成します。具体的な変更内容は次のとおりです: Validity: 0 は Validity: 1 に、Validity: 1 は Validity: 0 になります
- txtファイルのダウンロードをサポート
2. 方法 1
- 個人用コンテナ行を作成してドキュメントのすべてのコンテンツを読み取り、それを新しいファイルに書き込み、同じファイル名を持つ新しいファイルで古いファイルを上書きします (デバッグ中の txt エンコーディング ansi1 に対応)
- 欠点は時空オーバーヘッドが大きいことです
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> lines;
std::string line;
std::ifstream file("D:\\ugtrainning\\document\\information.txt");
if (file.is_open())
{
while (std::getline(file, line))
{
lines.push_back(line);
}
file.close();
}
else {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
std::string& line3 = lines[2];
if (line3 == "有效性:1") {
line3 = "有效性:0";
}
else if (line3 == "有效性:0") {
line3 = "有效性:1";
}
std::ofstream outfile("D:\\ugtrainning\\document\\information.txt");
if (outfile.is_open()) {
for (const auto& line : lines)
{
outfile << line << "\n";
}
outfile.close();
}
return 0;
}
3. 方法 2
- ポインタのオフセットを読み取ることで、検出後にドキュメントのコンテンツをその場で変更します
- 欠点は、txt のエンコード方法がオフセット桁数に影響を与えるため、エンコード方法に応じて調整する必要があることです。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream myfile("Information.txt");
string temp;
int i1,i2 = 0;
if (!myfile.is_open())
{
cout << "can not open this file" << endl;
return 0;
}
while(!myfile.eof()){
getline(myfile,temp);
if(i1==2 || i2==18){
if(temp[8]=='1'){
myfile.seekp(-3,ios::cur);
myfile<<"0";
getline(myfile,temp);
}
if(temp[8]=='0'){
myfile.seekp(-3,ios::cur);
myfile<<"1";
getline(myfile,temp);
}
i2=0;
}
i2++;
i1++;
}
myfile.close();
return 0;
}