问题描述
我正在尝试使用 ifstream 在 c++ 中打开一个文本文件,但即使该文件与 .cpp 文件位于同一目录中,它也找不到该文件:
I'm trying to open a text file in c++ with ifstream but it won't locate the file even though the file is in the same directory as the .cpp file:
#include <fstream>
std::ifstream textInput("words.txt");
if (!textInput) {
return false;
我已经三重检查,文件肯定存在并且命名正确.我不确定我的 ifstream 或路径是否有问题.
I've triple checked and the file definately exists and is named correctly. I'm not sure if I'm doing something wrong with ifstream or with the path.
我把文件放在visual studio的当前工作目录下,它显示文件的相对路径为words.txt",但仍然找不到文件.
I put the file in the current working directory of visual studio, it shows the files relative path as "words.txt", but it still can't find the file.
推荐答案
使用以下方法找出您的应用程序正在运行的位置(即所谓的当前工作目录"):
Find out where you application is running (what is know as the "current working directory") using:
TCHAR NPath[MAX_PATH];
GetCurrentDirectory(MAX_PATH, NPath);
std::cout << NPath << std::endl;
或者,如果您使用的是 C++17,则可以使用标准库:
Or if you are using C++17, you can do it using the standard library:
std::cout << std::filesystem::current_path().string() << std::endl;
确保文件位于与上述代码片段打印相同的路径中.
Make sure that the file is located in the same path as the above snippets print.
这篇关于ifstream 找不到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!