Sug*_*ara 1 c++ io fstream filepath
我能够创建文件,例如
f.open("file")
f.open("./path/file")
f.open("../path/file")
Run Code Online (Sandbox Code Playgroud)
但不是
f.open("~/path...)
f.open("/path...)
Run Code Online (Sandbox Code Playgroud)
我如何获得工作的绝对路径?
默认情况下,为输入和输出std::fstream::open(filename)
打开filename。因此该文件必须存在并且您必须对其具有写权限。
在您的情况下:
f.open("file")
f.open("./path/file")
f.open("../path/file")
Run Code Online (Sandbox Code Playgroud)
你很幸运。
在你的情况下:
f.open("~/path...")
Run Code Online (Sandbox Code Playgroud)
您使用了 path-element ~,这意味着$HOME在 shell 中,但仅意味着~在 C++ 中。
在这种情况下:
f.open("/path...")
Run Code Online (Sandbox Code Playgroud)
你很不幸:要么文件不存在,要么你没有写权限。
如果您只想打开文件以进行输入,则可以:
std::ifstreamstd::fstream f; f.open(filename,std::ios_base::in);如果您只想打开文件以进行输出,则可以:
std::ofstreamstd::fstream f; f.open(filename,std::ios_base::out);