/********************************************************************************* * Copyright: (C) 2023 LingYun IoT System Studio. * All rights reserved. * * Filename: mycp.c * Description: This file is ls command example code. * * Version: 1.0.0(2023年08月08日) * Author: Guo Wenxue * ChangeLog: 1, Release initial version on "2023年08月08日 17时17分00秒" * ********************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #define PROGNAME "myls" static int myls(char *path); int main (int argc, char **argv) { int fd; int i; if( 1 == argc ) { myls("."); return 0; } for(i=1; ipw_name); else printf("%d ", sbuf.st_uid); /* print group name or group id */ g = getgrgid (sbuf.st_gid); if( g ) printf("%s ", g->gr_name); else printf("%d ", sbuf.st_uid); /* print file size */ printf("%6lu ", sbuf.st_size); /* print time of last modification, Time functions: * https://www.jianshu.com/p/e92ced44f216 * https://blog.csdn.net/chen1415886044/article/details/106883544 */ t = (time_t)sbuf.st_mtim.tv_sec; ptm = localtime(&t); strftime(mtime, sizeof(mtime), "%b %e %R", ptm); printf("%s ", mtime); printf("%s", file); printf("\n"); return 0; } int myls(char *path) { struct stat sbuf; DIR *dirp; struct dirent *dir; char filepath[512]; /* Check file exist or not */ if( access(path, F_OK) ) { printf("%s: cannot access '%s': %s\n", PROGNAME, path, strerror(errno)); return -2; } stat(path, &sbuf); /* list file */ if( !S_ISDIR(sbuf.st_mode) ) { print_info(path); return 0; } /* list folder */ dirp = opendir(path); if( !dirp ) { printf("%s: cannot open directory '%s': %s\n", PROGNAME, path, strerror(errno)); return -3; } while( NULL != (dir=readdir(dirp)) ) { if( !strcmp(path, ".") ) strncpy(filepath, dir->d_name, sizeof(filepath)); else snprintf(filepath, sizeof(filepath), "%s/%s", path, dir->d_name); print_info(filepath); } return 0; }