General

Tech

Opening a txt file in XCode for a Cpp project

I'm trying to open a .txt file called "earth.txt" and I cannot get it to work. Normally you can just drag and drop your file into the SDK and it becomes a resource automatically, but that didn't work. I even tried deleting that file, creating a new file with the same name, then pasting the information inside of that new .txt, but that didn't work either. Here's a tidbit of my code:

ifstream inputfile;
inputfile.open ("earth.txt" );
if (!inputfile) {
cout << "Cannot open earth.txt" << endl;
exit (1)
}

And yes, I have the proper sharp include. I always get my error message and it closes. I've never had an issue with this on Microsoft's SDK. I even showed it to my prof and he couldn't figure it out. Id it different for XCode?

September 17, 2013

4 Comments • Newest first

bloodIsShed

replace
if (!inputfile)
with
if (inputfile.fail())

be sure to add a inputfile.close() when you're done

i could be wrong, but i think when you pass !inputfile as an argument, the program treat it as a number. since it's not 0, it considers to be true, so it executes whatever is inside the if statement. (since any non-zero number in c++ is considered true)

edit: or maybe try and specify the complete path as suggested above

Reply September 18, 2013 - edited
dragon2923

Rename file,modify code,test.

Kthxbai

Reply September 18, 2013 - edited
LiliKoby

you might have to specify the folder such as "admin(backslash x2)documents(backslash x2)earth.txt" or else its too hard to find the location and there can be multiple earth txts, at least for me (i'm using the microsoft 2012 compiler with <iostream> not the .h format)

Reply September 18, 2013 - edited
easyrolling

[quote=peterc1]is it inside a
main()

you could also pass it as an arguement or is that not part of the project?
Maybe the file is not in the same directory as your program or does xcode looks for the file in a source folder?
I am looking at it as it was c++[/quote]
it's apart of a .h currently but it's not working in the main either. It's in the same directory, and Xcode knows it's location.

Reply September 18, 2013 - edited