我能够创建这样的文件
f.open("file")
f.open("./path/file")
f.open("../path/file")
但不是
f.open("~/path...)
f.open("/path...)
如何获得工作的绝对路径?
最佳答案
默认情况下,std::fstream::open(filename)
为输入和输出打开 filename
。因此该文件必须存在并且您必须
有写权限。
在你的情况下:
f.open("file")
f.open("./path/file")
f.open("../path/file")
你很幸运。
在你的情况下:
f.open("~/path...")
您使用了路径元素 ~
,这意味着在 shell 中是 $HOME
但只是
在 C++ 中表示 ~
。
案例:
f.open("/path...")
你真不走运:要么文件不存在,要么你没有写权限。
如果您只想打开文件进行输入,则:
- 使用
std::ifstream
- 使用
std::fstream f; f.open(文件名,std::ios_base::in);
如果您只想打开文件进行输出,则:
- 使用
std::ofstream
- 使用
std::fstream f; f.open(文件名,std::ios_base::out);
关于C++ fstream 打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35825090/