简体   繁体   中英

Cant open a file in Visual Studio 2019

Hello I am currently following a book on c++ and currently learning on file i/o I am trying to open a .txt file and the result is everytime "could not open file

#include <iostream>
#include <filesystem>

using namespace std;

int main(int argc, char* argv[])
{
    ifstream file_reader("myfile.txt");
    if (!file_reader.is_open()) {
        cout << "could not open file" << "\n";
    }
    int number;
    file_reader >> number;

    return 0;
}

I'v tried to put the .txt file into debug folder and project folder but no success.

By default, Visual Studio C++ projects execute with the directory containing the .vcxproj file as the working directory (where all file operations are relative to).

You can see this if you right click your project in the "Solution Explorer" -> "Properties" menu item. The on the left of the new window select "Debugging". On the right the "Working Directory" item is most likely set to " $(ProjectDir) ".

project folder but no success.

So assuming you didn't change that setting, this should definitely work. Make sure you did place the file there, and that it is properly named (if using Explorer, be sure to have "File name extensions" enabled under "View", so you don't end up making like a myfile.txt.txt by mistake).

It is also possible opening the file fails for some other reason (unfortunately C++ error reporting on this is extremely limited). For example if the file permissions do not allow your program to read it.

If still no luck, you could maybe try writing a file, and see where it puts it.

ofstream file_writer("lostfile.txt");

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