Reputation: 611
I am using Mac and Xcode for my following code which should get my cin
value for the name
and the age
and write them in the file fileProcessingTrial.txt
.
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
// insert code here...
string name;
int age;
ofstream fileProcessing("fileProcessingTrial.txt", ios::out);
cout<<"Please enter your name: "<<endl;
cin>>name;
cout<<"Please enter your age: "<<endl;
cin>>age;
fileProcessing<<name<<" "<<age<<endl;
return 0;
}
And then where is my file fileProcessingTrial.txt
stored (by default?) if I want to open it? Can I store it in a specific location?
Upvotes: 2
Views: 2402
Reputation: 7445
I thought I would add an answer specific to Xcode. If you are building and running the executable in Xcode (the IDE), then the output file (if you did not specify an absolute path for the filename) will go to the same directory as the Build Products because that is where the built executable will be. This becomes the current working directory
mentioned by Jesper Juhl when Xcode runs the executable. To locate that, click on the product in the Project Navigator (in the below screenshot this is the File Out
executable in the left pane). Then look in the File Inspector in the upper right pane. The directory part of the Full Path is where your output file is.
If you did specify a relative path, then the location will be relative to this directory for build products, and as Jesper said, you should avoid encoding an absolute path in your program.
In Xcode, you can also change the current working directory
by editing the scheme:
Hope this helps.
Upvotes: 2
Reputation: 31475
If you do not specify a path (absolute or relative), then the file will be created in the current working directory
(aka CWD
) of the application at the time you create the file.
A program can change its CWD with chdir()
and obtain its current one with getcwd()
.
It is common for programs to change to some well known directory upon startup and do all their work there if they are daemons.
It is also common for some applications to determine the location of their executable (by reading /proc/self/exe
on Linux, for example) and then write files to a directory relative to that.
Other commonly used options are; writing to the users home directory or to a directory specified on the commandline or in a configuration file.
When you run a program from the shell, the CWD will initially be the directory the user was in when starting the application.
When running from a IDE, the CWD is usually set by the IDE to some location specified in its configuration.
In any case, avoid hard-coding absolute file paths in your program, since you can never be certain that path exist on all users machines (exceptions exist of course) nor that the user wants files written there. Best ask the user one way or another and write files to that location.
Upvotes: 2