如何将数据追加到存在数据的文件中
How to append the data into the file that exists data
我有一个文件的结构为:
A.txt 1
B.txt 2
C.txt 3
现在,我想打开文件并附加新数据,以便通过第二列添加2创建新数据,并且可以通过C/c++从该列获取数据的同一行例如
A.txt 1 3
式中3=1+2,1为第一行数据,2为加权因子最后,我期望的结果是
A.txt 1 3
B.txt 2 4
C.txt 3 5
我可以读取和获取数据,如:
FILE *fp;
fp=fopen('input.txt','a+');//Is it correct for append and read mode
if(!fp)
return -1;
int icheck=-1;
int thirdNum=0;
int num=0;
icheck= fscanf(fp, "%s %d", filename,&num);
thirdNum=num+2;
//How to append it to file as same row with the A.txt or B.txt or C.txt
Thank you so much
在c++中可以这样做:
#include <fstream>
#include <string>
#include <sstream>
#include <stdexcept>
int main() {
std::string filename = "file.txt", line;
std::ifstream ifs( filename.c_str(), std::ios::in);
if (!ifs) // check if the file exists and can be read
throw std::runtime_error( "cannot open the file");
std::stringstream buffer; // buffer to store the lines
while ( getline( ifs, line)) {
int previous_value;
std::istringstream iss(line.substr(line.find_last_not_of(" ")));
iss >> previous_value;
buffer << line << "t" << (previous_value + 2) << "n"; // add integer
}
std::ofstream ofs( filename.c_str(), std::ios::out); // ofstream buffer
ofs << buffer.rdbuf(); // write to the file
return 0;
}
如果避免将所有文件内容复制到临时缓冲区中,可以使内存效率更高。
相关文章:
- C++数据文件、数组和计算赋值
- 数据文件的第二行未正确读取
- 在 C++/C 中使用 CURL 发出带有数据文件的 GET HTTP 请求
- 将数据文件读入结构 C++
- 引入流时C++数据文件未正确读取?
- 如何在数据文件中查找和显示内容
- 如何处理错误"E1696命令行错误:无法在Visual Studio 2017中打开元数据文件"mscorlib.dll"?
- 尝试读取数据文件,存储在数组中并打印所有元素,但它不起作用
- 将数据文件读入对象数组时出现问题
- C :数据文件有错误:预期的无限制ID
- C 和 C++:带有错误"Expected unqualified-id"的数据文件
- 如何在C 中读取一系列数据文件
- 从数据文件中读取每2个字节,并在向量中进行比较
- 写入单个大数据文件或多个小文件:哪个更快?
- 在读取数据文件时,如何找到用户字符串输入的字谜?
- 保护外部数据文件免受未经授权的修改
- C 读取数据文件
- C 如何将数据文件读取到结构或向量以及返回结构或向量
- 具有挑战性的数据文件格式,需要将其读取为包含类对象的数组的VAR
- C 中的Google单元测试:如何编写持久数据文件