DEV Community

boiledsteak
boiledsteak

Posted on

C++ program can't find file when running in VScode?

I was doing my school assignment on C++ and I had issues with it while running my program in Visual Studio Code. It took me a stupidly long time to fix, and my google searches and ChatGPT prompts led to no where.

So if anyone faced the same issue as me, I hope this helps!

filename = "messy.txt";
fstream file(filename, fstream::in);
if (!file.fail()) 
{
   cout << "it works \n";
}
Enter fullscreen mode Exit fullscreen mode

Above is a simple C++ code snippet that reads a file named "messy.txt". If it works, the program prints out "it works ".
I had my .cpp and .exe in the same folder ad the messy.txt but the program still said it couldn't find the file.

Then I realised this only happened when I press the "play" or run button in vscode. If I did a manual g++ build command, the program can read the file when run.

Compiler issue then... I looked at launch.json inside the .vscode folder of my project (or the settings button beside the run button), and sure enough the "cwd" value was pointing to my compiler and not my project folder.

Yep so that fixed everything.

TLDR check launch.json "cwd" value

I'd love to include more screenshots but I don't want to reveal my personal machine's file paths and all. Contact me if you need help! See my profile for linkedin. I check quite often :)

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment José and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video 🎥

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay