C++: ofstream 类将文件保存到哪里?
我从 Windows 迁移到 Mac,现在遇到文件输入/输出类的问题:ifstream
& ofstream
。
在 Windows 中,当您使用 g++/Code Blocks 运行时,
ofstream out("output.txt");
out << "TEST";
out.close();
将在同一目录中创建一个新文件“output.txt”。
但是在 MAC OS X 中,此文件是在我的主目录中创建的: /Users/USER_NAME/output.txt
如何将此文件与可执行文件放在同一目录中?
PS 我正在使用 GCC 和 CodeBlocks。没有项目 - 我只是编译一个源文件。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
与所有其他文件打开函数一样,流类在您提供相对路径时使用当前目录。您可以使用诸如 chdir 之类的函数来控制当前目录,但更好的解决方案是使用完全限定的文件名。然后删除程序对当前目录的依赖。
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.该文件只是在当前工作目录中创建。更改工作目录或提供完整路径。
The file is simply created in the current working directory. Change working directory or provide full path.
工作目录是在程序启动时初始设置的。当您从命令行启动它时,您将从 shell 继承当前工作目录。在 CodeBlock 中,项目选项之一是用于调试运行的执行工作目录。
(另请参阅 http://www.gamedev.net /community/forums/topic.asp?topic_id=571206&whichpage=1�)
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�)
您需要提供您尝试创建的文件的完整绝对路径。
You'll need to provide a full, absolute path to the file you are trying to create.