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

Categories

0 votes
2.5k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...