【问题标题】:How to get directory of a file which is called from command line argument?如何获取从命令行参数调用的文件的目录?
【发布时间】:2011-07-29 12:33:57
【问题描述】:

例如,我在 ubuntu 中调用我的可执行文件:

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

我正在使用 realpath() 来查找 game1.txt 的路径。 但是,使用它会给我完整的路径,包括 game1.txt 名称。 例如,它将显示为

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

我想删除该字符串上的 game1.txt,以便我可以使用该字符串来输出该文件夹中的其他文件。 两个问题。

  1. realpath() 可以用于这种操作吗?有没有更好的办法?
  2. 谁能给我一个快速删除“game1.txt”的方法,以便将字符串“/home/*/Download/temp/”保存为字符串格式(不是字符) ?

非常感谢。

【问题讨论】:

    标签: c++ c file command-line-arguments realpath


    【解决方案1】:
     man -S3 dirname
    

    应该做你想做的事

    【讨论】:

      【解决方案2】:

      您可以为此使用 dirname 函数:http://linux.die.net/man/3/dirname

      注意 dirname 将擦除尾部斜杠(根目录除外);附加文件名时,您必须将斜杠重新附加。

      此外,您实际上不需要为此使用 realpath,您可以简单地使用传入的参数,dirname 将为您提供“temp”,您可以将文件名附加到该参数。

      【讨论】:

      • 这是正确的解决方案。除非您将调用 chdir 来更改工作目录,否则无需转换为绝对路径。
      【解决方案3】:

      不是很了解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.

      【讨论】:

        【解决方案4】:

        跨平台解决方案是

        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 也可以轻松做到这一点。我只是找到 QFileInfo 的文档很容易导航。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-06-07
          • 1970-01-01
          • 2010-09-14
          • 2013-08-23
          • 2020-03-29
          • 2023-03-05
          • 2016-09-17
          相关资源
          最近更新 更多