I am using linux g compiler and also visual studio code to compile and run the code below and each time I run it, it returns with could't open file. i have put the text file in the same folder as the c program but still to no avail. Can anyone point out where I have gone wrong?
The code:
#include <iostream>
#include <fstream>
#include <cstring>
#include <sstream>
using namespace std;
int main(int argc, char *argv[]) {
if (argc < 1) {
cerr << "Usage: " << argv[0] << "filename.txt" << endl;
}
ifstream ifile(argv[1]);
if (ifile.fail()) {
cerr << "Could not open file." << endl;
return 1;
}
return 0;
}
CodePudding user response:
Make sure that you have given the filename to the program as an argument.
After being compiled by g , you should run the program like this:
./program filename.txt
argv[1]
is the first program argument, in this case "filename.txt".Make sure that whatever launches the program is in the same working directory
Make sure that the file program has sufficient permissions to read the file. This can be changed with
chmod
.