为什么这不打开程序目录中的文件?
Why doesn't this open the file in the directory of the 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;
}
当我不提供任何参数时,它会在用户主目录中打开一个文件。这当然有道理。但是当我 运行 它来自这样一个不同的目录时:
$ ./folder/hometest examplefile
程序在我的当前目录而不是程序所在的目录中创建"examplefile"。
为什么会这样?
Why exactly is this happening?
程序运行正常。
文件是相对于当前工作目录打开的,而不是可执行文件所在的位置。
如果那样不行,
- 您的所有程序都必须使用绝对路径,或者
- 程序的位置将充满文件。首先,由于权限问题,这可能是不可能的。其次,在多用户系统中,用户最终会尝试创建相同的文件 names/directories.
以上都不可取。
我有这个小程序:
#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;
}
当我不提供任何参数时,它会在用户主目录中打开一个文件。这当然有道理。但是当我 运行 它来自这样一个不同的目录时:
$ ./folder/hometest examplefile
程序在我的当前目录而不是程序所在的目录中创建"examplefile"。
为什么会这样?
Why exactly is this happening?
程序运行正常。
文件是相对于当前工作目录打开的,而不是可执行文件所在的位置。
如果那样不行,
- 您的所有程序都必须使用绝对路径,或者
- 程序的位置将充满文件。首先,由于权限问题,这可能是不可能的。其次,在多用户系统中,用户最终会尝试创建相同的文件 names/directories.
以上都不可取。