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())
#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内容进行修改,具体修改如下:有效性:0变为有效性:1,有效性:1变为有效性:0
- 配套txt文档下载
2.方法1
- 创建一个人容器lines将文档内容全部读入,再写入新文件,通过相同文件名用新文件覆盖旧文件(调试时对应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;
}