C++: Where does the ofstream class save the files

2020-01-29 01:30发布

I moved from Windows to Mac and now I'm experiencing a problem with the file input/output classes: ifstream & ofstream.

In Windows when you run with g++/Code Blocks

ofstream out("output.txt");
out << "TEST";
out.close();

A new file "output.txt" will be created in the same directory.

However in MAC OS X, this file is created in my home directory: /Users/USER_NAME/output.txt

How can I have this file in the same directory together with the executable?

P.S. I'm using GCC and CodeBlocks. There are no projects - I'm just compiling a single source file.

4条回答
闹够了就滚
2楼-- · 2020-01-29 02:17

The file is simply created in the current working directory. Change working directory or provide full path.

查看更多
一夜七次
3楼-- · 2020-01-29 02:19

The working directory is initially set when your program starts. When you start it from the command line, you inherit the current working directory from the shell. In CodeBlock, one of the project options is the execution working dir' for debug runs.

(See also http://www.gamedev.net/community/forums/topic.asp?topic_id=571206&whichpage=1�)

查看更多
成全新的幸福
4楼-- · 2020-01-29 02:25

The stream classes, like all other file-opening functions, use the current directory when you provide a relative path. You can control the current directory with a function like chdir, but a better solution is to use fully qualified file names. Then you remove your program's dependency on the current directory.

查看更多
唯我独甜
5楼-- · 2020-01-29 02:29

You'll need to provide a full, absolute path to the file you are trying to create.

查看更多
登录 后发表回答