简体   繁体   English

如何获取从命令行参数调用的文件的目录?

[英]How to get directory of a file which is called from command line argument?

For example, I am calling my executable in ubuntu: 例如,我在ubuntu中调用我的可执行文件:

./foo temp/game1.txt temp/game2 txt ./foo temp / game1.txt temp / game2 txt

I am using realpath() to find the path to the game1.txt. 我正在使用realpath()查找game1.txt的路径。 Using it however will give me the full path including the game1.txt name. 但是使用它会给我完整的路径,包括game1.txt名称。 For example, it will come out as 例如,它将作为

/home/ * /Download/temp/game1.txt / home / * /下载/temp/game1.txt

I want to erase game1.txt on that string so that I can use the string to use it to output other files in that folder. 我想删除该字符串上的game1.txt,以便可以使用该字符串来输出该文件夹中的其他文件。 Two questions. 两个问题。

  1. Is realpath() alright to use for this kind of operation? realpath()是否可以用于此类操作? Is there better way? 有更好的办法吗?
  2. Can someone give me a quick way to erase "game1.txt" so that the string will be "/home/ * /Download/temp/" save in a string format(not char)? 有人可以给我一种快速的方法来擦除“ game1.txt”,以便字符串以“ / home / * / Download / temp /”保存为字符串格式(不是char)吗?

Thank you very much. 非常感谢你。

Don't really know Linux, but a general way for your second question: 并不是很了解Linux,但是您可以通过第二种常见的方式来解决这个问题:

#include <string>
#include <iostream>

int main(){
  std::string fullpath("/home/*/Download/temp/game1.txt");
  size_t last = fullpath.find_last_of('/');
  std::string path = fullpath.substr(0,last+1);

  std::cout << path;
}

See on Ideone . 见伊迪恩

You can use the dirname function for this: http://linux.die.net/man/3/dirname 您可以为此使用dirname函数: http : //linux.die.net/man/3/dirname

Note that dirname will erase the trailing slash (except for the root directory); 注意,dirname将删除尾部的斜杠(根目录除外); you'll have to append the slash back in when you append the filename. 您必须在添加文件名时重新添加斜杠。

Also, you don't actually need to use realpath for this purpose, you could simply use the argument as passed in, dirname will give you "temp" and you can append filenames to that. 同样,您实际上不需要为此目的使用realpath,您可以简单地使用传入的参数,dirname将为您提供“ temp”,并且可以将文件名附加到该文件中。

 man -S3 dirname

应该做你想做的

The cross-platform solution is 跨平台解决方案是

QFileInfo target_file_name(argv[1]);
QString absolute_path = target_file_name.absolutePath() 
// e.g. /home/username/

QString some_other_file = QString("%1/another_file.txt").arg(absolute_path) 
// => /home/username/another_file.txt

Boost.Filesystem can also do this easily. Boost.Filesystem也可以轻松做到这一点。 I just find the documentation of QFileInfo easily to navigate. 我只是发现QFileInfo的文档易于浏览。

http://doc.qt.nokia.com/4.6/qfileinfo.html#absolutePath http://doc.qt.nokia.com/4.6/qfileinfo.html#absolutePath

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

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