📄 opendir.c
字号:
/* *---------------------------------------------------------------------- * T-Kernel / Standard Extension * * Copyright (C) 2006 by Ken Sakamura. All rights reserved. * T-Kernel / Standard Extension is distributed * under the T-License for T-Kernel / Standard Extension. *---------------------------------------------------------------------- * * Version: 1.00.00 * Released by T-Engine Forum(http://www.t-engine.org) at 2006/8/11. * *---------------------------------------------------------------------- *//* * @(#)opendir.c (libg) * * Directory operation * * Use "SEIO" */#include <seio/dirent.h>#include <seio/fcntl.h>#include <seio/unistd.h>#include <seio/sys/types.h>#include <seio/sys/stat.h>#include <stdlib.h>#include <errno.h>/* * Open directory * Open the directory indicated by "path", and position it in the first directory entry. * Return value != "NULL" normal (return the access handle) * = "NULL" error (set "errno") */DIR* opendir( const char *path ){ DIR *dp; struct stat stat; dp = calloc(1, sizeof(DIR)); if ( dp == NULL ) { errno = ENOMEM; goto err_ret1; } /* Open the directory */ dp->dd_fd = open(path, O_RDONLY); if ( dp->dd_fd < 0 ) { goto err_ret2; } /* Check the adequate size as a read buffer */ if ( fstat(dp->dd_fd, &stat) < 0 ) { goto err_ret2; } /* Allocate a read buffer */ dp->dd_len = (int)stat.st_blksize; dp->dd_buf = malloc((size_t)dp->dd_len); if ( dp->dd_buf == NULL ) { errno = ENOMEM; goto err_ret3; } dp->dd_size = 0; dp->dd_loc = 0; return dp;err_ret3: (void)close(dp->dd_fd);err_ret2: free(dp);err_ret1: return NULL;}/* * Get directory entry * Retrieve 1 directory entry, and advance the current position to the next. * Return value != "NULL" normal (the retrieved directory entry) * = "NULL" end or error (set "errno" when error occurs) */struct dirent* readdir( DIR *dp ){ struct dirent *dent; int n; if ( dp->dd_loc >= dp->dd_size ) { /* Read into buffer */ n = getdents(dp->dd_fd, (struct dirent*)dp->dd_buf, (size_t)dp->dd_len); if ( n <= 0 ) { /* Error or termination */ return NULL; } dp->dd_size = n; dp->dd_loc = 0; } /* Directory entry of the current position */ dent = (struct dirent*)(dp->dd_buf + dp->dd_loc); /* Advance the current position */ dp->dd_loc += dent->d_reclen; return dent;}/* * Move to top * Reset "dp" to point out the top of directory. * By this setting, the directory becomes up-to-date,like the calling of "opendir() ". */void rewinddir( DIR *dp ){ (void)lseek(dp->dd_fd, 0L, SEEK_SET); dp->dd_size = 0; dp->dd_loc = 0;}/* * Close directory * Return value 0 normal * -1 error (set "errno") */int closedir( DIR *dp ){ int n; n = close(dp->dd_fd); free(dp->dd_buf); free(dp); return n;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -