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

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

例如,我在 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/”保存为字符串格式(不是字符) ?

非常感谢。

最佳答案

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

关于c++ - 如何获取从命令行参数调用的文件的目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5544790/

相关文章:

java - 如何使用 ImageIO 测试 BufferedImage 是否拾取 'null'

c++ - 如何在 MPI 中创建新类型

c++ - MFC、Unicode 和 DDX_Text

java - JNA 找不到函数

控制台图形帮助!

c - c 中的链表(从文件中读取)

android - Android无法提示安装apk文件

c++ - 与 Direct3D SpriteBatch 混合

c++ - LD_LIBRARY_PATH 不工作,而 LD_PRELOAD 工作正常

ios - 如何将数据写入项目目录中的文件?