Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any C APIs to extract the base file name from its full path in Linux?

Tags:

c

linux

Given the full path, the API should give me the base file name. E.g., "/foo/bar.txt" --> "bar.txt".

like image 355
341008 Avatar asked Jul 20 '10 08:07

341008


People also ask

How do I get filenames without an extension in Linux?

If you want to retrieve the filename without extension, then you have to provide the file extension as SUFFIX with `basename` command. Here, the extension is “. txt”.

How do I find the path of a directory in Linux?

To determine the exact location of your current directory within the file system, go to a shell prompt and type the command pwd. This tells you that you are in the user sam's directory, which is in the /home directory. The command pwd stands for print working directory.

How do I find the path of a file in bash?

In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.


1 Answers

There's basename() .

Feed it with a path (in the form of a char*) and it will return you the base name (that is the name of the file/directory you want) in the form of another char* .

EDIT:

I forgot to tell you that the POSIX version of basename() modifies its argument. If you want to avoid this you can use the GNU version of basename() prepending this in your source:

#define _GNU_SOURCE
#include <string.h>

In exchange this version of basename() will return an empty string if you feed it with, e.g. /usr/bin/ because of the trailing slash.

like image 98
Federico klez Culloca Avatar answered Sep 28 '22 11:09

Federico klez Culloca