【发布时间】:2020-12-18 23:06:04
【问题描述】:
我正在处理dev c++。我正在使用文件流打开一个已经放在文件夹中的文件。下面是我的代码。
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;
}
我的文件位于我的程序所在的同一文件夹中,即在我的C:\\Users\\Faisal\\Desktop\\Programs\\ 中。但是,我想使用相对路径,这样运行程序的人就可以访问该文件。
如何传递相对路径?
任何帮助将不胜感激。
【问题讨论】:
-
传递相对路径的方式与传递绝对路径的方式相同。例如。
file.open("somename.txt", ...) -
传递相对路径与传递绝对路径的方式完全相同,没有区别。当然,问题是您可能会弄错相对路径的相对位置。没有什么说它必须与程序文件夹相关。
-
相对路径可能有点棘手。如果你使用
somename.txt,它是相对于工作目录的,它不一定是应用程序的位置。 -
@IgorTandetnik 我试过这种方法,但没用
-
那么要么文件不在你认为的位置,要么当前工作目录不是你认为的那样。
标签: c++ string fstream dev-c++