【发布时间】:2021-01-04 11:25:25
【问题描述】:
我无法使用std::ifstream file 和file.open() 打开.txt 文件。我想使用间接 PATH(从 .exe 文件所在的文件夹开始 - \program_folder),但使用完整的 PATH (C:\Users\Rafael\Desktop\C++\program_folder\inputs\test.txt) 也不起作用。
#include <iostram>
#include <vector>
#include <string>
#include <fstream>
int main(){
char c;
std::vector<std::string> inputs;
inputs.push_back("C:\\inputs\\test.txt");
int a; int b;
std::ifstream file;
file.open(inputs[0]);
if (file.is_open()){
c = file.get();
file.close();
}
else {std::cout << "\nfail to open file";}
}
作为输出,我得到了失败消息。
【问题讨论】:
-
这意味着该文件在您所说的位置不存在,或者您没有读取它的权限。也许您将文件错误地命名为 test.txt.txt。 Windows 资源管理器默认隐藏扩展名,这可能导致已知文件具有双重扩展名。
-
arquivo.close();?? -
arquivo 是文件的葡萄牙语名称,我在翻译arquivo.close() 中的代码时错过了它
-
C++ 中没有标准的方法来使用相对于 exe 所在位置的路径。当前工作目录由平台设置,虽然可以更改,但没有标准的方法可以找出exe在哪里。
-
另外,
"C:\\inputs\\test.txt"不是相对路径,应该是"inputs\\test.txt"。
标签: c++ windows file debugging memory