如何解决将相对路径传递给ifstream c ++
我正在研究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,'\n');
}
//Close the file.
file.close();
return 0;
}
我的文件位于程序所在的文件夹中,即位于我的C:\\Users\\Faisal\\Desktop\\Programs\\
中。但是,我想使用相对路径,因此无论运行该程序的人都可以访问该文件。
如何通过相对路径?
任何帮助将不胜感激。
解决方法
考虑在unices上使用/tmp
目录,在Windows上使用System.IO.Path.GetTempPath()
。
如果您决定使用当前工作目录,则需要找到当前工作目录可执行文件cwd
,该可执行文件并非在所有平台上都位于同一位置。
也请检出https://en.cppreference.com/w/cpp/filesystem/current_path
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。