How to get directory of a file which is called fro

2019-09-03 16:16发布

For example, I am calling my executable in ubuntu:

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

I am using realpath() to find the path to the game1.txt. Using it however will give me the full path including the game1.txt name. For example, it will come out as

/home/*/Download/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. Two questions.

  1. Is realpath() alright to use for this kind of operation? 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)?

Thank you very much.

4条回答
不美不萌又怎样
2楼-- · 2019-09-03 16:51

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. I just find the documentation of QFileInfo easily to navigate.

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

查看更多
Root(大扎)
3楼-- · 2019-09-03 17:03
 man -S3 dirname

should do what you want

查看更多
爷的心禁止访问
4楼-- · 2019-09-03 17:10

You can use the dirname function for this: http://linux.die.net/man/3/dirname

Note that dirname will erase the trailing slash (except for the root directory); 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.

查看更多
我只想做你的唯一
5楼-- · 2019-09-03 17:11

Don't really know Linux, but a general way for your second question:

#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.

查看更多
登录 后发表回答