将相对路径传递给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