fs: add vlc_mkdir_parent function that correspond to 'mkdir -p'

This commit is contained in:
Gabriel LT 2024-03-12 13:12:54 +01:00 committed by Steve Lhomme
parent 908d899866
commit 2c853dd809
5 changed files with 69 additions and 0 deletions

View File

@ -275,6 +275,16 @@ VLC_API void vlc_rewinddir( vlc_DIR *dir );
*/
VLC_API int vlc_mkdir(const char *dirname, mode_t mode);
/**
* Creates a directory and parent directories as needed.
*
* @param dirname a UTF-8 string containing the name of the directory to
* be created.
* @param mode directory permissions
* @return 0 on success, -1 on error (see errno).
*/
VLC_API int vlc_mkdir_parent(const char *dirname, mode_t mode);
/**
* Determines the current working directory.
*

View File

@ -385,6 +385,7 @@ libvlccore_la_SOURCES = \
misc/mtime.c \
misc/frame.c \
misc/fifo.c \
misc/filesystem.c \
misc/fourcc.c \
misc/fourcc_list.h \
misc/es_format.c \

View File

@ -459,6 +459,7 @@ utf8_fprintf
vlc_loaddir
vlc_lstat
vlc_mkdir
vlc_mkdir_parent
vlc_mkstemp
vlc_open
vlc_openat

View File

@ -236,6 +236,7 @@ libvlccore_sources_base = files(
'misc/mtime.c',
'misc/frame.c',
'misc/fifo.c',
'misc/filesystem.c',
'misc/fourcc.c',
'misc/fourcc_list.h',
'misc/es_format.c',

56
src/misc/filesystem.c Normal file
View File

@ -0,0 +1,56 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
/*****************************************************************************
* filesystem.c: filesystem helpers
*****************************************************************************
* Copyright © 2024 VLC authors, VideoLAN and Videolabs
*
* Authors: Gabriel Lafond Thenaille <gabriel@videolabs.io>
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <vlc_common.h>
#include <vlc_fs.h>
/**
* Create all directories in the given path if missing.
*/
int vlc_mkdir_parent(const char *dirname, mode_t mode)
{
int ret = vlc_mkdir(dirname, mode);
if (ret == 0 || errno == EEXIST) {
return 0;
} else if (errno != ENOENT) {
return -1;
}
char *path = strdup(dirname);
if (path == NULL) {
return -1;
}
char *ptr = path + 1;
while (*ptr) {
ptr = strchr(ptr, DIR_SEP_CHAR);
if (ptr == NULL) {
break;
}
*ptr = '\0';
if (vlc_mkdir(path, mode) != 0) {
if (errno != EEXIST) {
free(path);
return -1;
}
}
*ptr = DIR_SEP_CHAR;
ptr++;
}
ret = vlc_mkdir(path, mode);
if (errno == EEXIST) {
ret = 0;
}
free(path);
return ret;
}