Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the full path for a filename command-line argument?

Tags:

c++

c

linux

macos

I've found lots of libraries to help with parsing command-line arguments, but none of them seem to deal with handling filenames. If I receive something like "../foo" on the command line, how do I figure out the full path to the file?

like image 355
Roland Rabien Avatar asked Nov 02 '09 15:11

Roland Rabien


Video Answer


2 Answers

You could use boost::filesystem to get the absolute path of a file, from its relative path:

namespace fs = boost::filesystem;
fs::path p("test.txt");
fs::path full_p = fs::complete(p); // complete == absolute
std::cout << "The absolute path: " << full_p;
like image 96
Khaled Alshaya Avatar answered Oct 19 '22 03:10

Khaled Alshaya


POSIX has realpath().

#include <stdlib.h>
char *realpath(const char *filename, char *resolvedname);

DESCRIPTION
The realpath() function derives, from the pathname pointed to by filename, an absolute pathname that names the same file, whose resolution does not involve ".", "..", or symbolic links. The generated pathname is stored, up to a maximum of {PATH_MAX} bytes, in the buffer pointed to by resolvedname.

like image 26
pmg Avatar answered Oct 19 '22 03:10

pmg