qq_36018270
2017-10-12 07:56
采纳率: 100%
浏览 8.2k

C++文件写入时会覆盖之前的数据

在不过是用ofstream还是fstream打开文件,也用过ios::app|ios::out或者ios::in|ios::out都在写入的时候会覆盖之前的内容,开始以为是输出的问题,但是我在用eof遍历时候(输入几行)但是只能谁出一行。

#include
#include
#include
using namespace std;
struct Book
{
char Name[20];
int No;
int Num;
float Price;
};
void main()
{

fstream booklist("booklist.txt", ios::binary | ios::trunc | ios::in | ios::out);
if (!booklist)
{
cout << "Can't open the file" << endl;
exit(1);
}
Book BL;
for (int i = 1; i < 4; i++)
{
cout << "请输入第" << i << "种书的名字、编号、库存量和价格" << endl;
cin >> BL.Name >> BL.No >> BL.Num >> BL.Price;
//Book head1;
//head1 = NULL;
//createmsg(Book *head1);
booklist.write((char
)&BL, sizeof(Book));
}
for (int i = 4; i >2; i--)
{
booklist.seekg((i - 1)*sizeof(Book), ios::beg);
booklist.read((char*)&BL, sizeof(Book));
booklist.write((char*)&BL, sizeof(Book));
}
cout << "请输入第" << 10 << "种书的名字、编号、库存量和价格" << endl;
cin >> BL.Name >> BL.No >> BL.Num >> BL.Price;
booklist.seekg(10 * sizeof(Book), ios::beg);
booklist.write((char*)&BL, sizeof(Book));
int count = 0;
int sum = 0;
booklist.seekg(0, ios::beg);
cout << "书名" << '\t' << "编号" << '\t' << "库存量" << '\t' << "价格" << endl;
//for (int i = 0; i < 4; i++)
//{
while(!booklist.eof())
{
booklist.read((char*)&BL, sizeof(Book));
cout << BL.Name << '\t' << BL.No << '\t' << BL.Num << '\t' << BL.Price << endl;
count += BL.Num;
sum += BL.Num*BL.Price;
}
cout << "总库存量是:" << count << '\t' << "总价格为:" << sum << endl;
getchar();
return;
}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • oyljerry 2017-10-12 08:29
    已采纳

    用append模式

     fstream booklist("booklist.txt", ios::binary | ios::app | ios::in | ios::out);
    
    点赞 打赏 评论
  • IronLavender 2017-10-12 12:41

    楼上正解,C语言也是这样,一般默认就是直接覆盖,如果要追加就设置append

    点赞 打赏 评论
  • Grade_Fish 2017-10-13 05:55

    位置设置到文件末尾啊

    点赞 打赏 评论
  • qq_35643290 2017-10-19 07:08

    同意一楼二楼的说法,C语言也是这样,一般默认就是直接覆盖,如果要追加就设置append

    点赞 打赏 评论

相关推荐 更多相似问题