1

I have a file in my Xcode directory for this project, and the program will open it, but when I input something, it won't save to the file. Not sure why.

std::string entry;
std::fstream file;

file.open ("a1bc3.txt", std::ios::out | std::ios::in );

if (!file.is_open()){
    std::cin >> entry ;
}
else {
    std::cout << "Failed to open.\n" ;
}

file << entry << std::endl ;
file.close();
return 0;
Universe31
  • 45
  • 3
  • 5
    Look *carefully* at your if statement checking if the file opened successfully. – eesiraed Jun 04 '19 at 04:00
  • Your answer is here: https://stackoverflow.com/questions/31483349/how-can-i-open-a-file-for-reading-writing-creating-it-if-it-does-not-exist-w – fukanchik Jun 04 '19 at 04:02
  • "when I input something" - if you even can input something, it means your program (this program) couldn't open the file due to the broken misplaced `!` applied to `file.is_open()`. The ensuing write is meaningless because the stream is already broken. Otherwise the file is (a) opened, (b) you're never prompted, and (c), nothing is written to the file, which is then closed. Also, make sure your working directory is set in your project scheme. The default run-location for an Xcode project is the build folder; not the project folder. – WhozCraig Jun 04 '19 at 04:04
  • @WhozCraig , I'm an idiot, removed the ! and changed by derived data library to the folder where the .txt file is located, but now my code just tells me it's failed to open the file. Still not too sure, I'm still learning. – Universe31 Jun 04 '19 at 04:35
  • XCode may be running the program from a different working directory than you expect. [Use `getcwd`](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/getcwd.3.html) to find out where the program's been told to start and then move your text file to that directory or change the working directory. – user4581301 Jun 04 '19 at 05:06

0 Answers0