[英]Why doesn't this open the file in the directory of the program?
I have this short program: 我有这个简短的程序:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
int main (int argc, char * argv[]) {
std::string homedir = std::getenv("HOME");
std::string filename = argc > 1 ? argv[1] : (homedir + "/" + "file");
std::cout << homedir << std::endl;
std::cout << filename << std::endl;
std::fstream file;
file.open(filename, std::ios::out);
file << "Yo yo waddup" << std::endl;
file.close();
return 0;
}
When I supply no arguments, it opens a file in the users home directory. 当我不提供任何参数时,它将在用户的主目录中打开一个文件。 That of course makes sense.
那当然是有道理的。 But when I run it from a different directory like this:
但是当我从这样的不同目录运行它时:
$ ./folder/hometest examplefile
The program creates "examplefile" in my current directory instead of the directory where the program is. 该程序在我的当前目录而不是该程序所在的目录中创建“ examplefile”。
Why exactly is this happening? 为什么会这样呢?
Why exactly is this happening?
为什么会这样呢?
The program is behaving just as expected. 该程序的行为与预期的一样。
The file is opened relative to the current work directory, not where the executable is located. 相对于当前工作目录而不是可执行文件所在的位置打开文件。
If it didn't work that way, 如果不是那样的话
Neither of the above is desirable. 以上都不是理想的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.