c++linuxvisual-studio-code

Trouble reading a file with C++ in vs code, not sure if this is because I'm working within Linux


Im trying to read the contents of a file in C++, but when I go to run the program it keeps failing. Not sure if this is because I'm using ubuntu linux.

Code below: seems basic enough but for some reason the file never opens and continues to fail

  // This program reads data from a file.
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
   // Create a text string, which is used to output the text file
string myText;

// Read from the text file
ifstream MyReadFile;
MyReadFile.open("nums");

if(!MyReadFile){
  cout << "Failed" << endl;
}
else 

// Use a while loop together with the getline() function to read the file line by line
  while (getline (MyReadFile, myText)) {
  // Output the text from the file
    cout << myText;
  }

// Close the file
MyReadFile.close(); 
}

Solution

  • Your file won't be open because you're missing the full path to it and the extension. If your file is in your "home" directory for example, you should write

    MyReadFile.open("/home/nums.txt");
    

    Here is another answer from stack overflow: How do you open a file in C++?