Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ basic file i/o, failure to read

I am trying to replicate an exercise from a text book, however the file never reads and so the if statement is triggered telling me that I have not read the file. I have no error message or warnings. I am sure I am missing something fundamental but I just don't know what it could be.... I am running OSX, Clang7.0, using Qt (but I have also tried this in sublime text and it fails there too)

here is the code:

#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    ifstream file_reader ( "myfile.txt" );
    if ( !file_reader.is_open() )
    {
        cout<<"Could not open file!"<<'\n';
    }
    int number;
    file_reader >> number;
    cout<<number;
}

The file is in the same directory as the program files. It is a .txt file simply containing:

12 a b c 

I have tried putting the full path and had a look at some similar threads but it does not seems to be the same problem as this

Thanks for any help in advance

like image 835
Harry de winton Avatar asked Jul 11 '26 03:07

Harry de winton


1 Answers

As pointed out by others, many IDEs compile your program in some other directory, but they generally also provide a way to copy required files into that same location. Xcode is a case in point. If you find out where your program was created, put myfile.txt in that directory, invoke your program as `./myprogram', and your code will work.

If you want to see what directory your program is running from, you can use getenv("PWD") to look up the working directory, and then do whatever you need to with it.

#include <fstream>
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    cout << "PWD = " << getenv("PWD") << endl; // Inspect working directory

    ifstream file_reader ( "myfile.txt" );
    if ( !file_reader.is_open() )
    {
        cout << "Could not open file!" << endl;
        return -1; // If the file wasn't opened, there's no point in going on
    }
    int number;
    file_reader >> number;
    cout << number << endl;
    return 0; // Always return 0 from main() if successful
}

As you discovered, Documents on OS X lives in your home directory, which would be something like /Users/myusername. Double-quotes are necessary in the shell if your path or file name includes spaces or special characters, but are not necessary from inside your program (i.e. your ifstream() initialization), because the argument will not be interpreted by a shell. The ~ is likewise interpreted by the shell but not by the standard libraries or kernel, which is why using it inside your program doesn't work: ~/ is not a directory name.

like image 78
Josh Sanford Avatar answered Jul 13 '26 21:07

Josh Sanford



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!