2017-08-05 72 views
-2

我正在嘗試創建清單程序。需要包含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(); 

} 
+0

你使用的ofstream ....不是.... ifstream的你 –

+0

標題說,「從文件讀取」你的代碼寫入到一個!?另外,什麼是「Item」的聲明我有一個偷偷摸摸的懷疑,那就是它不是一個POD,在這一點上你不能把它寫到像你現在這樣做的文件中。 – Borgleader

+0

嗨,是的,但是當我寫數據的時候,我認爲這個問題正在發生。我有一個display()函數,我打電話後,它只開始顯示垃圾後,我添加了ios :: app – Kubie

回答

0

爲了解決這個問題,我只好打電話給ios::ate而不是ios::app標誌。我還必須使用fstream數據類型而不是ofstream數據類型,即使我只寫入文件。

下面是對這個問題怎麼可以troubleshooted更多詳細信息:Opening a binary output file stream without truncation