Not able to open file using fstream

82 Views Asked by At

I think I may not have the file I'm trying to read in the right spot but i've put it everywhere possible in the IDE and it is still not working. Ive even put it next to the .exe for my program and it still cant find it.

enter image description here

I was expecting the file to be able to be opened so I can read its contents with c++ code.

#include <iostream>
#include <fstream>       
#include <cstdlib>  // exit prototype
#include <iomanip>

using namespace std;

int main(int argc, char* argv[])
{
    ifstream inFile;
    string filename = "infile6";
    // if a filename is provided, open file
    cout << "Enter the name of a file to read from: " << endl;
    //cin >> filename;
    cout << "Name of a file requested: " << filename << endl;

    inFile.open(filename.c_str());
    if (!inFile)
    {
        cerr << endl;
        cerr << "File cannot be opened" << " " << filename << endl;
        exit(1);
    }

    return 0;  // ifstream destructor closes file

} // end main
1

There are 1 best solutions below

0
neg-c On

The default location of projects created with Visual Studio is:

C:\Users\%USERNAME%\Documents\Visual Studio 2022\Projects

replace Visual Studio 2022 with your version

Your binary file is located deep inside that directory tree

Most likely :

C:\Users\%USERNAME%\Documents\Visual Studio 2022\Projects\RA2\Debug\RA2.exe or C:\Users\%USERNAME%\Documents\Visual Studio 2022\Projects\RA2\Debug\RA2.exe

RA2/
    ├── RA2.sln
    ├── RA2.vcxproj
    ├── RA2.vcxproj.filters
    ├── Debug/
    │   └── RA2.exe
    ├── Source Files/
    │   └── main.cpp
    ├── Header Files/
    │   └── ...
    ├── Resource Files/
    │   └── ...
    └── ...

Now, your program is expecting the file infile6 to be located in the same directory as your executable(C:\Users\%USERNAME%\Documents\Visual Studio 2022\Projects\RA2\Debug\).

You can either copy/paste your file in that directory, or you can provide the absolute path to your infile6.

Here is the absolute path ssuming your username is Bob and Visual Studio version 2022

string filename = "C:\\Users\\Bob\\Documents\\Visual Studio 2022\\Projects\\RA2\\Source Files\\infile6";

P.S if you use C++17 you should take advantage of std::filesystem to deal with file paths, its cleaner, safer, and the modern way.