C ++:ofstream类将文件保存到哪里? [英] C++: Where does the ofstream class save the files to?
问题描述
我从Windows移动到Mac,现在我遇到了文件输入/输出类的问题: ifstream
& ofstream
。
I moved from Windows to Mac and now I'm experiencing a problem with the file input/output classes: ifstream
& ofstream
.
在Windows中使用g ++ /代码块运行
In Windows when you run with g++/Code Blocks
ofstream out("output.txt");
out << "TEST";
out.close();
将在同样中创建一个新文件output.txt目录。
A new file "output.txt" will be created in the same directory.
但在MAC OS X中,此文件在我的主目录中创建:/Users/USER_NAME/output.txt
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?
PS我使用GCC和CodeBlocks。没有项目 - 我只是编译一个源文件。
P.S. I'm using GCC and CodeBlocks. There are no projects - I'm just compiling a single source file.
UPDATE
我刚刚在XCode中运行相同的代码,它的工作确定!这些文件在项目的Debug目录中创建。
I just ran the same code in XCode, and it works ok! The files are created in project's Debug directory.
所以这不是操作系统的问题。它是Code :: Blocks for Mac。如何在Code :: Blocks中更改工作目录?
So it's not operating system's problem. It's Code::Blocks for Mac. How can I change work directory in Code::Blocks?
推荐答案
流类与所有其他文件打开函数一样,使用当前目录提供相对路径。您可以使用 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.
这篇关于C ++:ofstream类将文件保存到哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!