macos C++:ofstream 类将文件保存到哪里?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4017034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++: Where does the ofstream class save the files to?
提问by Alex
I moved from Windows to Mac and now I'm experiencing a problem with the file input/output classes: ifstream
& ofstream
.
我从 Windows 转移到 Mac,现在我遇到了文件输入/输出类的问题:ifstream
& ofstream
。
In Windows when you run with g++/Code Blocks
在 Windows 中使用 g++/代码块运行时
ofstream out("output.txt");
out << "TEST";
out.close();
A new file "output.txt" will be created in the samedirectory.
将在同一目录中创建一个新文件“output.txt” 。
However in MAC OS X, this file is created in my home directory: /Users/USER_NAME/output.txt
但是在 MAC OS X 中,这个文件是在我的主目录中创建的:/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.
PS 我正在使用 GCC 和 CodeBlocks。没有项目 - 我只是编译一个源文件。
回答by Rob Kennedy
The stream classes, like all other file-opening functions, use the current directorywhen 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.
与所有其他文件打开函数一样,流类在您提供相对路径时使用当前目录。您可以使用类似 的函数控制当前目录,但更好的解决方案是使用完全限定的文件名。然后删除程序对当前目录的依赖。chdir
回答by ?imon Tóth
The file is simply created in the current working directory. Change working directory or provide full path.
该文件只是在当前工作目录中创建的。更改工作目录或提供完整路径。
回答by MSalters
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.
工作目录最初是在程序启动时设置的。当您从命令行启动它时,您将从 shell 继承当前工作目录。在 CodeBlock 中,项目选项之一是调试运行的执行工作目录。
(See also http://www.gamedev.net/community/forums/topic.asp?topic_id=571206&whichpage=1�)
(另见http://www.gamedev.net/community/forums/topic.asp?topic_id=571206&whichpage=1 )
回答by Edward Strange
You'll need to provide a full, absolute path to the file you are trying to create.
您需要提供您尝试创建的文件的完整绝对路径。