简体   繁体   English

为什么不打开程序目录中的文件?

[英]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, 如果不是那样的话

  1. All your programs will have to work with absolute paths, or 您的所有程序都必须使用绝对路径,或者
  2. The location of the program will be flooded with files. 程序的位置将充满文件。 First, that might not be possible because of permissions issue. 首先,由于权限问题,这可能无法实现。 Second, in a multi-user system, users will end up trying to create the same file names/directories. 其次,在多用户系统中,用户最终将尝试创建相同的文件名/目录。

Neither of the above is desirable. 以上都不是理想的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM