使用 ifstream 和 QtCreator 从当前目录读取文件
我正在使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 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.
会的;你的代码很好。但正如其他答案所暗示的那样,您需要确保在您认为的目录中运行它。
在左侧面板上选择“项目”,然后(从顶部的选项卡中)选择“运行设置”,它将显示在标有“工作目录”的字段中运行可执行文件的位置。我认为默认情况下它是发布和调试文件夹上方的目录。
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.
Visual Studio 和 Qt Creator 之间的区别可能在于,
尝试使用 this 获取当前目录然后查看它是否确实包含该文件。
The difference between Visual Studio and Qt Creator may be that
Try to get the current directory using this and then see if it actually contains the file.