2014-09-13 209 views
0

我嘗試了很多解決方案,沒有任何工作,絕對和相對路徑。我也改變了目錄,等等。我的代碼總是以這種方式工作,我不知道什麼是錯的。FStream讀取txt文件

兩個我所做的例子:

// Read a file into memory 
#include <iostream>  // std::cout 
#include <fstream>  // std::ifstream 

int main() { 
    std::ifstream is ("test.txt", std::ifstream::binary); 
    if (is) { 
     // Get length of file: 
     is.seekg (0, is.end); 
     int length = is.tellg(); 
     is.seekg (0, is.beg); 

     char * buffer = new char [length]; 

     std::cout << "Reading " << length << " characters... "; 

     // Read data as a block: 
     is.read (buffer,length); 

     if (is) 
      std::cout << "all characters read successfully."; 
     else 
      std::cout << "error: only " << is.gcount() << " could be read"; 
     is.close(); 

     // ...buffer contains the entire file... 
     std::cout << buffer; 
     system("PAUSE"); 
     delete[] buffer; 
    } 
    return 0; 
} 

char pfad[256]; //The path to the application is stored here. 
_getcwd(pfad, 256); 
std::string truepfad; 
truepfad = pfad; 
truepfad.append("\\test.txt"); 
fstream f("C:\\Users\\Etix\\Documents\\test.txt"); 
string s; 
if (!f) 
    std::cout << truepfad; 
else 
{ 
    std::cout << "open file"; 
    while (getline(f, s)){ 
     std::cout << s; 
    } 
} 
+1

任何錯誤訊息? – lxg 2014-09-13 13:43:30

回答

0

在使用你的代碼,我得到的錯誤是:

Error: Expected a declaration. 

Error: This declaration has no storage class or type specifier. 

我認爲這個問題可能是你錯過了一些#include的。我看到你需要#include < string>和其他幾個以及第44行 (包含#include < string>)的錯誤語句。

+0

切勿使用名稱空間標準; 您可以在C++中執行最大的初學者錯誤。 錯誤是由於我的窗口配置錯誤,代碼很好,我不知道爲什麼你得到這個錯誤,但你做錯了什麼。 – user3718058 2014-10-12 11:36:35

+0

我個人認爲可以用小型項目來做,但我同意使用名稱空間標準的更大的項目;會很糟糕。 – Chantola 2014-10-12 14:33:00