util: introduce virDirRead wrapper for readdir

Introduce a wrapper for readdir. This helps us make sure that we always
set errno before calling readdir and it will make sure errors are
properly logged.

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Eric Blake <eblake@redhat.com>
This commit is contained in:
Natanael Copa 2014-04-20 13:53:45 +02:00 committed by Eric Blake
parent fbcd9d3252
commit 1ce2f1a434
3 changed files with 38 additions and 0 deletions

View File

@ -1222,6 +1222,7 @@ safewrite;
safezero; safezero;
virBuildPathInternal; virBuildPathInternal;
virDirCreate; virDirCreate;
virDirRead;
virFileAbsPath; virFileAbsPath;
virFileAccessibleAs; virFileAccessibleAs;
virFileActivateDirOverride; virFileActivateDirOverride;

View File

@ -2391,6 +2391,39 @@ virDirCreate(const char *path ATTRIBUTE_UNUSED,
} }
#endif /* WIN32 */ #endif /* WIN32 */
/**
* virDirRead:
* @dirp: directory to read
* @end: output one entry
* @name: if non-NULL, the name related to @dirp for use in error reporting
*
* Wrapper around readdir. Typical usage:
* struct dirent ent;
* int value;
* DIR *dir;
* if (!(dir = opendir(name)))
* goto error;
* while ((value = virDirRead(dir, &ent, name)) > 0)
* process ent;
* if (value < 0)
* goto error;
*
* Returns -1 on error, with error already reported if @name was
* supplied. On success, returns 1 for entry read, 0 for end-of-dir.
*/
int virDirRead(DIR *dirp, struct dirent **ent, const char *name)
{
errno = 0;
*ent = readdir(dirp);
if (!*ent && errno) {
if (name)
virReportSystemError(errno, _("Unable to read directory '%s'"),
name);
return -1;
}
return !!*ent;
}
static int static int
virFileMakePathHelper(char *path, mode_t mode) virFileMakePathHelper(char *path, mode_t mode)
{ {

View File

@ -27,6 +27,7 @@
# define __VIR_FILE_H_ # define __VIR_FILE_H_
# include <stdio.h> # include <stdio.h>
# include <dirent.h>
# include "internal.h" # include "internal.h"
# include "virstoragefile.h" # include "virstoragefile.h"
@ -225,6 +226,9 @@ enum {
}; };
int virDirCreate(const char *path, mode_t mode, uid_t uid, gid_t gid, int virDirCreate(const char *path, mode_t mode, uid_t uid, gid_t gid,
unsigned int flags) ATTRIBUTE_RETURN_CHECK; unsigned int flags) ATTRIBUTE_RETURN_CHECK;
int virDirRead(DIR *dirp, struct dirent **ent, const char *dirname)
ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_RETURN_CHECK;
int virFileMakePath(const char *path) ATTRIBUTE_RETURN_CHECK; int virFileMakePath(const char *path) ATTRIBUTE_RETURN_CHECK;
int virFileMakePathWithMode(const char *path, int virFileMakePathWithMode(const char *path,
mode_t mode) ATTRIBUTE_RETURN_CHECK; mode_t mode) ATTRIBUTE_RETURN_CHECK;