C++: ofstream 类将文件保存到哪里?

发布于 2024-09-29 03:58:18 字数 429 浏览 8 评论 0原文

我从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

情深缘浅 2024-10-06 03:58:18

与所有其他文件打开函数一样,流类在您提供相对路径时使用当前目录。您可以使用诸如 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.

妄司 2024-10-06 03:58:18

该文件只是在当前工作目录中创建。更改工作目录或提供完整路径。

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

绮烟 2024-10-06 03:58:18

工作目录是在程序启动时初始设置的。当您从命令行启动它时,您将从 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�)

深居我梦 2024-10-06 03:58:18

您需要提供您尝试创建的文件的完整绝对路径。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文