简体   繁体   中英

FStream read txt file

I tried many solutions, nothing works, absolute and relative paths. I changed directories as well, etc. My code always worked this way, and I got no clue what can be wrong.

Two examples of what I did:

// 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;
}

and

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;
    }
}

The errors I get while using your code are:

 Error: Expected a declaration.

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

I think the problem might be that your missing some #include's. I saw you need #include <string> and several others as well as an improperly made if statement at line 44 (with the #include <string>).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM