csguy
csguy

Reputation: 1474

Unable to Open .txt File

std::ifstream infile;   
infile.open("example.txt");

if (!infile.is_open()) {        
   std::cout << "can't open" << std::endl;  
}

I read this: unable to open file stream c++ and have tried using the full path infile.open("~/projects/example.txt");

The text file is in the same folder where the .cpp / .hpp files reside.

What else could be the problem?

Upvotes: 0

Views: 430

Answers (2)

zkoza
zkoza

Reputation: 2860

I once had the same problem on Windows. The problem was that the actual file name was "example.txt.txt", but Window Explorer was configured (by default) to hide file extensions.

A simple solution is to use c++17 filesystem library. For example, current_path will return what its name promises. Or write a simple function that will list the current path contents (see the example on cppreference, https://en.cppreference.com/w/cpp/experimental/fs/directory_iterator ) . Or create a file of some similar name, e.g. __example__.txt and see where it was created and under which name it is reported by your filesystem manager.

If this is Linux, try running your program under strace (strace myprog myoptions).

Upvotes: 1

Ben
Ben

Reputation: 56

try "realpath ~/projects/example.txt", which will show you the real path of your file, and then use this real path in your cpp

Upvotes: 1

Related Questions