2015-05-02 24 views
2

我試圖從文件中讀取和寫入一對int對。該文件將是這個樣子:從文件中讀取和寫入int對

0 6 
12 24 
48 33 
23 24 
80 79 

我的目標是讀每一對到一個結構:

struct foo { 
    int a; 
    int b; 
} 

,然後按每個結構到堆棧。然而,fstreams已被證明相當難以處理這項任務。現在,我的文件中讀取的代碼如下所示:

std::fstream fileStream(file, std::ios::in); 
int a, b; 
while (fileStream >> a >> b) { 
    myStack.push({ a, b }); 
} 

我的輸入可能是這樣的(我必須單獨做,因爲什麼,我使用它...的):

inputFoo(foo bar) { 
    std::fstream fileStream(file, std::ios::out); 
    fileStream << bar.a << " " << bar.b; 
} 

但是,我有一種感覺,這不是我應該如何有效和安全地做到這一點。我也有來檢查,如果該文件已經存在的功能,但我不知道那一個作品之一:

bool fileExists() { 
    std::ifstream stream; 
    return stream.good(); 
} 

什麼是真正做到這一點的最好方法是什麼?

+0

我會使用ifstream和ofstream而不是fstream – pjsofts

+0

而對於文件的存在,如果性能是一個問題:http://stackoverflow.com/questions/12774 207 /最快的方式檢查,如果一個文件存在使用標準c-c11-c – pjsofts

回答

2

你不需要fileExists()功能。該函數中的流甚至沒有打開。只是檢查像這樣:現在

std::fstream fileStream(file, std::ios::in); 

if(!fileStream.is_open()) 
{ 
    // handle the error 
} 

,如果你願意,也有不改變邏輯幾點建議:

  • 使用std::ifstream輸入,你可以省略std::ios::in參數
  • 輸出使用std::ofstream,你可以省略std::ios::out參數
  • 超載<<>>運營foo

    struct foo 
    { 
        int a; 
        int b; 
    
        foo() : a(0), b(0) {} // default constructor to make it a little more c++ and less c 
    
        friend std::istream &operator>>(std::istream &is, foo &f); 
    
        std::ostream &operator<<(std::ostream &os) 
        { 
         return os << a << " " << b; 
        } 
    }; 
    
    // Both can be friend, only operator<< can be member 
    std::istream &operator>>(std::istream &is, foo &f) 
    { 
        return is >> f.a >> f.b; 
    } 
    

    到你可以通過不僅文件流,但例如std::cinstd::cout(可能是調試和控制檯輸入輸出有用)。你會讀到這樣的:

    foo f; 
    
    while(fileStream >> f) 
        myStack.push(f); 
    

    而寫的更簡單:

    fileStream << bar; 
    

至於你的評論,這是在我腦海中的唯一的事情:

const std::string filePath = "file.txt"; 
std::ifstream ifs(filePath); 

if(ifs.is_open()) 
{ 
    // read 
} 
else 
{ 
    std::ofstream ofs(filePath); 

    // write 
} 
+0

謝謝!有一個關於文件存在的問題:我想要做的是讀取文件,如果它存在,並創建/開始寫入文件,如果它不存在。我將如何使用fstream.open()? – user3760657

+0

我面臨的一個問題是:當我執行fileStream >> f時,它給了我一個錯誤:找不到操作符類型爲std :: ifstream(或沒有可接受的轉換)的左操作數的操作符。我實現了foo運算符重載,並且它與thestream一起工作,但ifstream在那裏提供了它的問題。有針對這個的解決方法嗎? – user3760657

+1

@ user3760657對不起,更新了答案。 – LogicStuff

4

做這樣

std::ifstream fileStream(file, std::ios::in); 

while (!fileStream.eof()) { 
    foo f; 
    fileStream >> f.a>> f.b 
    myStack.push(f); 
} 

循環將結束的整個文件讀

寫作會是這樣

std::ofstream fileStream(file, std::ios::in); 

while (!myStack.isEmpty()) { 
    foo f; 
    f=myStack.pop(); 
    fileStream << f.a<<" "<< f.b<<endl; 

} 
+0

謝謝!把foos寫到文件上怎麼樣? – user3760657

+0

[請閱讀本文](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered- wrrong) – LogicStuff

+0

閱讀編輯後的答案 –