Having trouble with fstream in Xcode

南笙酒味 提交于 2020-01-30 08:47:03

问题


I'm having trouble validating the existence of REGISTER.txt for input purposes in a function (see below). My understanding is that if the file doesn't exist, then the file won't be opened and the file stream variable (inData) will be false. Thus, I can use that variable in an if/else statement to verify whether or not it opened. But even though REGISTER.txt is in the same directory as my .cpp file, my code still says that it wasn't opened.

Here's the thing though. When I run the same exact code in Dev-C++ compiler, it works fine and the file is found. Now, I understand compilers are different, but I don't understand what is causing the discrepancy here. My preferred IDE is Xcode, so I'd like to learn how to do I/O with files in Xcode.

Thanks in advance for the help.

P.S. My Xcode project references the file, so it's not like the project isn't connected with the file.

void ReadVehicleRegInfo(char& vehicleType, string& licensePlate,
                    int& modelYear, float& origTaxValue, bool& error)
{
    ifstream inData;

    string inputFile = "REGISTER.txt";
    inData.open(inputFile.c_str());        //File contains registration info

    if (!inData) {
        //File does not exist. Exit function
        cout << inputFile << " does not exist. Program will now terminate"
             << endl << endl;
        error = true;

        return;
    } else {
        //File exists - continue with program
        cout << inputFile << " found";
    }

    inData.close();
}

In my main() function, I have the following code to signal to the user that an error has occurred:

if (error) {
    //Function encountered error. Exits program
    system("PAUSE");
    return 99;
}

EDIT I spent 40 minutes trying to figure this out, 15 writing the question, and 5 minutes after I post it I make huge progress. Don't you love that?

I put in the full directory to the file and that did the trick.

However, this is not ideal. The next question is how do I avoid having to do that? What is the default directory for Xcode?


回答1:


REGISTER.txt is in the same directory as my .cpp file

REGISTER.txt needs to be in the same directory as the binary (build/Release or elsewhere depending on your build settings)




回答2:


Normally it would be the directory where your program lives. If you want to make sure, use _getcwd to get the current directory or just include the parent directory.

char *_getcwd( char *buffer, int maxlen );

However, you should try not to use the full path for the reason it might not be the same when you run your program on another computer.



来源:https://stackoverflow.com/questions/19672887/having-trouble-with-fstream-in-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!