FStream读取txt文件

时间:2014-09-13 13:38:24

标签: c++ fstream

我尝试了很多解决方案,没有任何作用,绝对和相对路径。我也改变了目录,等等。我的代码总是以这种方式工作,我不知道哪些是错的。

我所做的两个例子:

// 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 个答案:

答案 0 :(得分:0)

我在使用您的代码时遇到的错误是:

 Error: Expected a declaration.

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

我认为问题可能是你错过了一些#include&#39; s。我看到你需要#include &LT;串GT;和其他几个以及第44行的不正确的if声明 (使用#include&lt; string&gt;)。