从文件提供垃圾的C++ fstream阅读
问题描述:
我正在尝试创建清单程序。需要包含ios :: app以覆盖inventory.txt文件中的数据,比如ios :: out,但是当我添加ios :: app数据时,已经在损坏/垃圾中读取。我想这个问题归结为这一行: outfile.open(“inventory.txt”,ios :: out | ios:app | ios :: binary);从文件提供垃圾的C++ fstream阅读
我粘贴给我下面的问题的功能。
谢谢!
void add() {
Inventory Item;
int recnum;
ofstream outfile;
// opening file
outfile.open("inventory.txt", ios::out | ios:app | ios::binary);
if (outfile.fail())
cout << "\nFile failed to open" << endl;
cout << "\nPlease enter the record ID to be added (will overwrite duplicates) : ";
cin >> recnum;
cout << "\n" << recnum << " has been set as the record ID for this item." << endl;
cout << "Please enter item description in 50 characters or less : ";
cin.ignore();
cin.getline(Item.description, size);
// do-whiles below are for looping for input validation
do {
cout << "Please enter the number of items on hand : ";
cin >> Item.quantity;
if (Item.quantity < 0)
cout << "Please enter a valid number." << endl;
} while (Item.quantity < 0);
do {
cout << "Please enter the wholesale price for this item : ";
cin >> Item.wholesale;
if (Item.wholesale < 0.01)
cout << "Please enter a valid number." << endl;
} while (Item.wholesale < 0.01);
do {
cout << "Please enter the retail price for this item : ";
cin >> Item.retail;
if (Item.retail < 0.01)
cout << "Please enter a valid number." << endl;
} while (Item.retail < 0.01);
// couldn't figure out how to perform input validation for date
cout << "Please enter the date this item was added (format: mm/dd/yyyy) : ";
cin.ignore();
cin.getline(Item.dateadded, datesize);
// finding position in file, writing to file, closing file
outfile.seekp(recnum*sizeof(Item), ios::beg);
outfile.write(reinterpret_cast<char *>(&Item), sizeof(Item));
outfile.close();
}
答
为了解决这个问题,我只好打电话给ios::ate
而不是ios::app
标志。我还必须使用fstream
数据类型而不是ofstream
数据类型,即使我只写入文件。
下面是对这个问题怎么可以troubleshooted更多详细信息:Opening a binary output file stream without truncation
你使用的ofstream ....不是.... ifstream的你 –
标题说,“从文件读取”你的代码写入到一个!?另外,什么是“Item”的声明我有一个偷偷摸摸的怀疑,那就是它不是一个POD,在这一点上你不能把它写到像你现在这样做的文件中。 – Borgleader
嗨,是的,但是当我写数据的时候,我认为这个问题正在发生。我有一个display()函数,我打电话后,它只开始显示垃圾后,我添加了ios :: app – Kubie