2015-04-01 68 views
-1

我有一個允許用戶輸入新記錄(放入結構然後寫入文件),打印所有記錄或編輯特定記錄的程序。我已經包含了我的功能。這些記錄是針對girlcout cookie信息的。它有名稱,數量,價格和成本。它打開文件,要求用戶輸入名稱,然後當它找到名稱時,它將所有數據讀入臨時結構變量(與寫入文件的相同),用戶可以在其中更改數量和重寫它在它被讀取的同一個地方。除了更新的數量之外,所有內容都應該是相同的。它會執行所有這些操作,但由於某種原因會將所有其他記錄變爲null或0之前的所有其他記錄。我的錯誤是什麼讓這個改變了我文件中的所有其他記錄。我只想編輯這個特定的一個。 這只是功能。幫助真的很感激!C++ fstream通過.txt搜索結構

功能代碼:

void editField() 
{ 
    char input[20]; 
    fstream data("cookies.txt", ios::in); 
    cookies test; 

    if (!data) { 
     cout << "Error opening file. Program aborting.\n"; 
     return; 
    } 

    cout << "Please enter the name of the cookie you are searching for: "; 
    cin.getline(input,20); 

    data.read(reinterpret_cast<char *>(&test), 
    sizeof(test)); 

    while (!data.eof()) 
    { 
     if(strcmp(input,test.name) == 0) { 

      int position = data.tellp(); 
      data.close(); 
      data.clear(); 
      data.open("cookies.txt", ios::binary | ios::out); 

      cout << "Please enter the new quantity for the cookie "; 
      cin >> test.quantity; 

      data.seekp(position-sizeof(test),ios::cur); 
      data.write(reinterpret_cast<char *>(&test), sizeof(test)); 
     } 
     // Read the next record from the file. 
     data.read(reinterpret_cast<char *>(&test), 
     sizeof(test)); 
    } 
    return; 
} 
+0

像往常一樣'while(!data.eof())'是錯誤的 - 我沒有讀過去(在這樣做之後,這段代碼是垃圾) – 2015-04-01 20:32:44

+0

這段代碼並不按原樣編譯。請發佈有問題的[最小示例](http://stackoverflow.com/help/mcve) – chwarr 2015-04-01 20:52:46

+0

這不能編譯?我現在正在運行它?我是包含的#include 的#include 的#include 的#include 的#include 的#include 的#include Reaperr 2015-04-01 20:57:52

回答

0
  • 變化while(!data.eof())while(data)
  • 爲了清晰起見,在你while循環的開始從文件中讀取一個記錄,而不是結尾。
  • 當您的記錄被寫入時,您可以跳出循環。
  • 寫cookies.txt時,用std::ios::binary | std::ios::in | std::ios::out打開它。從std::ios::beg尋找。
  • 您可以同時讀取和寫入文件。這應該起作用,但沒有必要。在寫入之前先關閉文件進行閱讀。
+0

謝謝!它只是在ios :: out時默認創建一個新文件。我應該已經知道的東西。感謝您對新手的尊重和幫助! – Reaperr 2015-04-01 21:11:31