从导出的文件夹中读取文件
Reading a file from an exported folder
我有一个文件(我们称之为"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;
}
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中