I'm currently learning file I/O in C++.
I can open the file by using the full directory of the .txt file which is C:\Users\mfkha\cmsc202\inclass\scores.txt.
The path of the program file is C:\Users\mfkha\cmsc202\inclass\Lesson 4.cpp.
However, when I am using scores.txt, the program can't find the file.
Here is the source code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <ctime>
#include <fstream>
using namespace std;
int main() {
string fName;
string lName;
int score;
// ifstream myFile("testfile.txt"); // OPTION 1
ifstream myFile;
myFile.open("C:\\Users\\mfkha\\cmsc202\\inclass\\scores.txt"); // OPTION 2
if (myFile.is_open()) {
while(myFile >> fName && myFile >> lName && myFile >> score) {
cout << fName << " " << lName << " " << score << endl;
}
myFile.close();
}
else{
cout << "No file found" << endl;
}
return 0;
}
I can't open the file when I was using file name, I have to use full path tof the file, someone please help.
Every process has a working directory, initially set to the directory from which the executable was launched.
For instance, if the executable
g++is run from "C:\users\bob\Desktop", the process will start with its working directory set to "C:\users\bob\Desktop".File paths must be specified relative to this working directory, or as absolute paths from the filesystem's root directory.
For example, if Lesson4.cpp is compiled into an executable named
lesson4in "C:\users\bob\Desktop", accessing "testfile.txt" requires the file be in the same directory as from where the executable was launched.It is possible to change the working directory of your process using the system call "chdir()".
To access "testfile.txt" in your case, either use
chdir()to switch to its directory or execute the resulting binary from your C++ code from the same directory as "testfile.txt".