2014-03-07 86 views
1

我正在嘗試編寫一個程序,該程序將文本文件的內容顯示給用戶的屏幕。具體來說,該文本文件將是程序將讀取並向用戶單獨顯示每個名稱的名稱列表。然後用戶會喜歡這個名字,並保留或不喜歡這個名字並將其刪除。C++:如何在文件的輸入和輸出之間切換?

我的兩難處境是:如果用戶選擇保留名稱,程序將需要從讀取文件到「寫入」(刪除名稱)文件,然後再返回到讀取文件!我在http://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm上找到了以下相關代碼。它表明必須使用.close()從閱讀轉換爲書寫,但對於像我這樣的新手來說,這看起來很時髦。有沒有更好的方法來做到這一點,或者是下面的代碼就好了?

#include <fstream> 
#include <iostream> 
using namespace std; 

int main() 
{ 

    char data[100]; 

    // open a file in write mode. 
    ofstream outfile; 
    outfile.open("afile.dat"); 

    cout << "Writing to the file" << endl; 
    cout << "Enter your name: "; 
    cin.getline(data, 100); 

    // write inputted data into the file. 
    outfile << data << endl; 

    cout << "Enter your age: "; 
    cin >> data; 
    cin.ignore(); 

    // again write inputted data into the file. 
    outfile << data << endl; 

    // close the opened file. 
    outfile.close(); 

這是文件從寫入模式變爲讀取模式的地方。

// open a file in read mode. 
    ifstream infile; 
    infile.open("afile.dat"); 

    cout << "Reading from the file" << endl; 
    infile >> data; 

    // write the data at the screen. 
    cout << data << endl; 

    // again read the data from the file and display it. 
    infile >> data; 
    cout << data << endl; 

    // close the opened file. 
    infile.close(); 

    return 0; 
} 

另外,我有一個很難找到如何讀取和文件中修改單個字符。我也需要這樣做,因爲文件需要遵循特定模式,每行有五個名稱,每個名稱之間有一個空格(顯然,第五個名稱末尾的換行符)。幫助與此將不勝感激。

+0

讓你的文件進入緩衝區(名稱),做你的操作(如刪除)並將更改後的緩衝區保存到文件中。對文件進行並行輸入/輸出操作非常棘手。 – zoska

回答

1

嘗試

std::fstream ff("io.txt", std::fstream::in | std::fstream::out);

fstream::read, fstream::write, fstream::seekg

0

如果該文件是小然後將其加載到內存中。 否則使用fopen以「a +」或「r +」模式和fseek

2

改變事物中間文件是複雜

我會做的是既可以創建一個臨時文件,寫入不停名該文件,並替換該臨時文件中的原始文件,(或者只是存儲在一個載體保持名稱和重寫文件)