简体   繁体   中英

unable to open file stream c++

I am working with Xcode and I am having trouble opening a file stream to assign variables from a text file. I speculate that placing the txt file in the same directory as the project would allow me open the stream without including the entire dir. I have been messing with this for a little while to no avail can I get it to work properly. I believe I was able to read data at one point, but I think the string printed was in unicode (not sure). It is a very simple program.. I would think that it would work. I think my problem has to do with the directory the example is in and how Xcode works with project files. I just put the example file in the project folder and hoped that it would work.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
int main()
{
    string name;
    ifstream infile;
    infile.open("example.txt");
    if(infile.is_open())
    {
        infile >> name;
    }
    else
        cout << "Unable to open file";

    cout << name;
    return 0;
}

First of all, remember, that working directory is not always the same directory where the program's binary resides.

Change:

infile.open("example.txt");

to:

infile.open("/full/path/to/program/directory/example.txt");

where /full/path/to/program/directory/ is the location of folder, where program (and thus example.txt file) is placed. It should fix the issue.


By the way, you may also want to read this question , that addresses very similar problem.

Also, read about getcwd() function .

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