从导出的文件夹中读取文件

Reading a file from an exported folder

本文关键字:读取 文件 文件夹      更新时间:2023-10-16

我有一个文件(我们称之为"file.txt"),它位于文件夹/folder/where/the/file/is中。并且这个文件夹已经导出到$FOLDER,比如如果我这样做:

echo $FOLDER,我得到:folder/where/the/file/is

现在,我想测试该文件是否存在。

所以,我试过了

  ifstream ifile(Name_finput);
  if(!ifile.good()){  
  cout << "File doesn't exist !" << endl;
  return;
  }

这在Name_finput = "/folder/where/the/file/is/file.txt"有效,但如果Name_finput=$FOLDER/file.txt则无效

有没有办法通过保持表单$FOLDER/file.txt来工作?编译器似乎没有将$FOLDER解释为/folder/where/the/file/is

$FOLDER C++代码无效。为了访问环境变量,您需要使用 std::getenv() 。代码应如下所示:

#include <iostream>
#include <cstdlib>
#include <fstream>
int main() {
    std::ifstream ifile;
    if (const char* e = std::getenv("FOLDER")) {
        ifile.open(std::string(e) + std::string("/file.txt"));
        if (!ifile.is_open()) {
            std::cout << "File doesn't exist !" << std::endl;
        } else {
            // Do-stuff with the file
        }
    }
    return 0;
}