Search code examples
c++fstream

Can't get basic file input to work! (fstream)


Why won't my program open my .txt document? The document is at the specified location. And I know that \i is not an Escape Sequence.

#include <iostream>
#include <fstream>

using namespace std;

int main(){
    fstream fin("C:\\input.txt");

    if (!fin)
    {
        cerr << "Error, couldn't open txt file!" << endl;
        return 1;
    }

    return 0;
}

Solution

  • You can alternatively use this code to input any file that is stored at C:\\text.txt into console window.

    #include<iostream>
    #include<fstream>
    using namespace std;
    
    int main() {
    
     ifstream myReadFile;
     myReadFile.open("D:\\text.txt");
     char output[100];
     if (myReadFile.is_open()) {
        while (!myReadFile.eof()) {
            myReadFile >> output;
            cout << output;
        }
    }
    
    myReadFile.close();
    return 0;   
    }