Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

c++ - ifstream can't find file

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;

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.

EDIT: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...