2

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;
}

查看全部
qq_36018270
qq_36018270
2017/10/12 07:56
  • c++
  • 文件读写
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

4个回复