When I wrote the following code on my iMac Xcode, it does not write anything into the file "data.txt"; however, the same code works on Visual Studio 2019 on a window 10 laptop. Can it be explained?
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
fstream myfile;
myfile.open ("data.txt");
myfile << "This is a new message.\n";
myfile.close();
return 0;
}
Thanks a lot! Still not working. When I try the second option, it did not pop up anything at all.(not even the "Program ended with exit code:0"). Is it possible that my iMac has a configuration that blocks reading and writing into an existing file? By the way, my C++version implemented is "201402" (std::cout << __cplusplus << std::endl;),
Problem solved! It is tricky. I had previously put the data.txt in the same directory as main.cpp and thought it would be fine. All you need to do is specify the directory
While that might solve your immediate issue, it's not a good practice because it hardcodes an absolute path on your system. This might not matter for a personal project, but would matter for projects that you would expect multiple people to use; it's important to understand what the working directory of the program is.
its confusing at first. the console path is where the thing is, absolutely, so if you move to folder/somewhere/ and type a.out it runs because its in that folder.
but you could go up a level to folder. Then if you type something like /somewhere/a.out it works, because you told it where to go, but if you just type a.out, its not there.
SOME ides run out of a path that is handy for the current project but the executable file is elsewhere, and when you run it to debug it, it just invokes it like we did above; /somewhere/a.out and it runs it like that. The catch is, that when you do that, a.out only sees what is in your current path, not the /somewhere/ folder. So if a.out expects file foo.txt to be in the same folder that it is in, that works in the first example: both files are in the folder where you ARE in the console. But the other examples, where we tap the program from another folder with a path, the program can't find the file, because it looks from where it was called. So calling it from the folder above in the console or the IDE doing something similar, it can't find the file.
Does you see this?
visual studio does the same thing. It hides the windows executable in a doofy folder and running it from the IDE vs running it from the commandline give the same kinds of problems.
Xcode IDE enables setting of a custom working directory via the menu as follows:
Product->Scheme->Edit Scheme->Run->Options, then 'Working directory' about 3/4 way down.