2016-11-21 121 views
0

我正在尋找我的問題的答案,但我沒有在任何其他地方找到它。閱讀.txt文件的問題

我正在嘗試從.txt文件中讀取,該文件位於與我的項目文件相同的目錄中。

我寫了這個簡單的代碼:

ifstream file("file.txt"); 
std::string line; 
std::getline(file, line); 
cout << line; 

...但不幸的是,什麼也沒發生,甚至不是一個錯誤或崩潰。

進一步探索後...即使我將txt(「文件」)文件的名稱更改爲不存在的文件的名稱,也沒有任何反應。

我錯過了什麼?

回答

-2

如果您的錯誤是由於打開文件,然後provide full path to the file並檢查。

在你的代碼中你正在閱讀第一行,所以如果它是一個空格,那麼你可以看不到任何輸出。

您必須迭代每行直到最後一行(到達文件EOF的末尾)。

// let's say your file is "test.txt" which is located in D\\MyDB 
// ifstream file("file.txt"); 

ifstream file("D:\\MyDB\\test.txt"); // use full path instead and check manully whether the file is there or not 
std::string line; 

if(file.fail()) 
    cout << "Opening file failed!" << endl; 
else 
    while(std::getline(file, line)) 
    { 
     cout << line; 
    } 

如果它在提供完整路徑時工作,那麼您的當前路徑與您的項目不同。

,你可以使用一些API改變當前目錄,所以如果你在Windows上運行:SetCurrentDirectory(path);和Linux上使用:chdir(sDirectory.c_str());

**我的意思是編譯器不OS

+0

仍然沒有成功,我現在寫這行:cout <<「錯誤打開文件:」<< strerror(errno);我得到:「沒有這樣的文件或目錄」,我錯過了什麼? – Realto

+0

@Realto請問您的文件在哪裏添加完整路徑。 – Raindrop7

+0

/Users/John/ClionProjects/MyProject – Realto

0

你怎麼知道沒有錯誤?你沒有檢查。

#include <cerrno> 

然後

ifstream file("file.txt"); 
if (file) // is the file readable? 
{ 
    std::string line; 
    if (std::getline(file, line)) // did we manage to read anything? 
    { 
     cout << line; 
    } 
    else 
    { 
     cout << "File IO error"; 
    } 
} 
else 
{ 
    cout << "error opening file: " << strerror(errno); 
} 

執行初步檢查。

+0

感謝快速answer.to更清楚,程序運行時不會崩潰,但是當我運行你的代碼時,我得到了「錯誤打開文件」。所以我怎麼知道我做錯了什麼? – Realto

+0

@Realto添加了一些代碼來打印*爲什麼*文件無法打開。 – user4581301

+0

好吧,所以我得到這個錯誤:「沒有這樣的文件或目錄」,買什麼?我把文件放在包含所有項目文件的目錄中,我想念什麼? – Realto