使用 ifstream 和 QtCreator 从当前目录读取文件

发布于 2024-12-27 09:32:27 字数 293 浏览 3 评论 0原文

我正在使用 Qt Creator 来创建一个没有 Qt 库的普通 C++ 项目。

我正在尝试打开这样的文件:

fopen("text.txt", "r");

或者

ifstream fin;
fin.open("text.txt");

但它不能像 Visual Studio 中那样仅使用文件名,我必须传递完整路径才能打开文件...

有人知道这是为什么吗?以及如何在不使用 Qt 库的情况下引用当前目录?

I'm using Qt Creator for a plain C++ project without the Qt libraries.

I'm trying to open a file like this:

fopen("text.txt", "r");

or

ifstream fin;
fin.open("text.txt");

But it doesn't work with just the filename like in Visual Studio, I have to pass the full path for it to open the file...

Anybody knows why is that? and how can I refer to the current directory without using Qt libs?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

浮华 2025-01-03 09:32:27

您可以使用 QDir::current() 来检查工作目录是否是您想要的目录。如果没有 Qt,您可以使用链接到的 ToMA 解决方案

运行设置允许您将其配置为运行来自 IDE 的应用程序。

You can use QDir::current() to check wether the working directory is what you want it to be. Without Qt you can use the solution TomA linked to.

The run settings allow you to configure it for running the application from the IDE.

↘紸啶 2025-01-03 09:32:27

会的;你的代码很好。但正如其他答案所暗示的那样,您需要确保在您认为的目录中运行它。

在左侧面板上选择“项目”,然后(从顶部的选项卡中)选择“运行设置”,它将显示在标有“工作目录”的字段中运行可执行文件的位置。我认为默认情况下它是发布和调试文件夹上方的目录。

It will; your code is fine. But as other answers allude, you need to make sure you're running it in the directory you think you are.

On the left panel select "Projects" then (from the tabs at the top) "Run Settings" and it will show you where it runs the executable from in the field labeled "Working directory". I think by default it's the directory above the release and debug folders.

白云悠悠 2025-01-03 09:32:27

Visual Studio 和 Qt Creator 之间的区别可能在于,

  1. 它们各自在项目结构的不同子目录中启动程序二进制文件。
  2. 一个确实将 text.txt 文件作为项目的一部分复制到与二进制文件相同的输出目录,另一个则没有。

尝试使用 this 获取当前目录然后查看它是否确实包含该文件。

The difference between Visual Studio and Qt Creator may be that

  1. Each starts the program binary in a different subdirectory of your project structure.
  2. One does copy the text.txt file as part of your project to the same output directory as the binary, the other does not.

Try to get the current directory using this and then see if it actually contains the file.

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