#include <>
It is a header file in the C/C++ language, mainly used for string processing, especially when processing file paths. It provides some functions to help you parse file names and directory paths.
Main functions
The following isSome common functions:
basename(char *path)
:
- Function: Returns the basic file name in the given path (remove the path part).
- Example:
#include <> #include <> int main() { char path[] = "/home/user/"; printf("Base name: %s\n", basename(path)); // Output: "" return 0; }
dirname(char *path)
:
- Function: Returns the directory part of the given path (remove the file name).
- Example:
#include <> #include <> int main() { char path[] = "/home/user/"; printf("Directory name: %s\n", dirname(path)); // Output: "/home/user" return 0; }
Notes on using
-
Modify the input string: These functions usually modify the input string (i.e.
path
Parameters). Therefore, the passed string should be modifiable (usually an array, not a string constant). -
Return pointer: The returned pointer points to the passed parameter, so if the same is used again later
path
, need to be reset. -
Not suitable for complex paths:
basename
anddirname
The expected results may not be provided for some complex paths, such as paths containing multiple consecutive slashes or paths ending with slashes.
Sample program
Below is a complete program that demonstrates how to use itbasename
anddirname
:
#include <> #include <> #include <> int main() { char path[] = "/home/user/"; // Copy the original string to avoid basename/dirname modifying it char path_copy[256]; strncpy(path_copy, path, sizeof(path_copy)); printf("Original path: %s\n", path); printf("Base name: %s\n", basename(path_copy)); // Output: "" // Re-copy the original string to get the directory name strncpy(path_copy, path, sizeof(path_copy)); printf("Directory name: %s\n", dirname(path_copy)); // Output: "/home/user" return 0; }
Summarize
Provided
basename
anddirname
Functions are very convenient and can effectively help process and parse file paths. When performing file operations, using these two functions reasonably can simplify your code.
This is the article about how to parse file names and directory paths in C/C++. For more related contents of C/C++ parsing file names and directory paths, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!