c++ - 添加到文件而不删除里面的内容

标签 c++

我正在编写一段代码,它从用户那里获取一些输入并将其存储在一个文件中。我的代码应该保留旧数据并添加新数据,但每次运行代码时,文件中的旧数据都会被新数据替换。

if(input == 1){
             outFile.open("personnel2.dat");
             int numRecords = 0;
             do{
                 cout << "#1 of 7 - Enter Employee Worker ID Code(i.e AF123): ";
                 cin >> id;
                 cout << "#2 of 7 - Enter Employee LAST Name: ";
                 cin >> lastN;
                 cout << "#3 of 7 - Enter Employee FIRST Name: ";
                 cin >> firstN;
                 cout << "#4 of 7 - Enter Employee Work Hours: ";
                 cin >> workH;
                 cout << "#5 of 7 - Enter Employee Pay Rate: ";
                 cin >> payRate;
                 cout << "#6 of 7 - Enter FEDERAL Tax Rate: ";
                 cin >> federalTax;
                 cout << "#7 of 7 - Enter STATE Tax Rate: ";
                 cin >> stateTax;
                 outFile << id << " " << lastN << " " << firstN << " " << workH << " " << payRate << " "
                         << federalTax << " " << stateTax << "\n";
                 numRecords++;
                 cout << "Enter ANOTHER Personnel records? (Y/N): ";
                 cin >> moreRecords;
             }while(moreRecords != 'N' && moreRecords != 'n');

             outFile.close();
             cout << numRecords << " records written to the data file.\n";

             }

最佳答案

更改outFile.open("personnel2.dat");

outFile.open("personnel2.dat", std::fstream::app);

将模式设置为附加,假设您正在使用 fstream::open()

关于c++ - 添加到文件而不删除里面的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54498954/

相关文章:

c++ - 如何混合 32 位整数?或 : Why is there no _mm256_blendv_epi32?

c++ - Objective-C:如果我在 ARC 的函数中返回一个 C++ 对象,它会创建一个拷贝吗?我是否必须手动释放该拷贝?

c++ - 声明静态类变量

C++ 在美国日期的 COleDateTime 中 LCID 的正确用法是什么

c++ - 为什么C++标准要求std::partition来满足不同类型迭代器的不同复杂度?

未知原因的 C++ libpthread 程序段错误

c++ - Freeglut glew glutIdleFunc 导致滞后

c++ - 在重载的 operator new 中初始化类成员是否未定义?

c++ - 通过两次链接同一个库来解决循环依赖?

C++ "HTTP"服务器 - 分块数据传输