I am working on dev c++
. I am using file stream to open a file which is already placed in a folder. Below is my code.
int main(){
ifstream file; // File stream object
string name; // To hold the file name
//Write the path of the folder in which your file is placed
string path = "C:\\Users\\Faisal\\Desktop\\Programs\\";
string inputLine; // To hold a line of input
int lines = 0; // Line counter
int lineNum = 1; // Line number to display
// Get the file name.
cout << "Enter the file name: ";
getline(cin, name);// Open the file.
string fileToOpen = path + name + ".txt";
file.open(fileToOpen.c_str(),ios::in);// Test for errors.
if (!file){
// There was an error so display an error
// message and end the PROGRAM.
cout << "Error opening " << name << endl;
exit(EXIT_FAILURE);
}
// Read the contents of the file and display
// each line with a line number.
// Get a line from the file.
getline(file, inputLine, '\n');
while (!file.fail()){
// Display the line.
cout << setw(3) << right << lineNum<< ":" << inputLine << endl;
// Update the line DISPLAY COUNTER for the next line.
lineNum++;// Update the total line counter.
lines++;// If we've displayed the 24th line, pause the screen.
if (lines == 24){
cout << "Press ENTER to CONTINUE...";
cin.get();
lines = 0;
}
// Get a line from the file.
getline(file, inputLine, '\n');
}
//Close the file.
file.close();
return 0;
}
My file is in the same folder where my program resides i.e. in my C:\\Users\\Faisal\\Desktop\\Programs\\
. However, I want to use a relative path, so whoever runs the program can access the file.
How can I pass the relative path?
Any help would be highly appreciated.