ls -al 命令的简单实现(C语言版)
这篇是承接自我的上一篇文章(ls命令的简单实现),其中大部分函数的实现没有改变,我将修改后的函数展示在了下面。另外附上 *.c文件函数的全部实现,方便没看过我上一篇文章的读者阅览。
// ls.h
// 头文件内容有所改变
#include <stdio.h> // printf()
#include <string.h> // strcmp() strcpy() memset()
#include <stdlib.h> // malloc() free()
#include <dirent.h> // opendir() closedir() readdir()
#include <unistd.h> // getcwd();
// 增加
#include <sys/stat.h> // stat()
#include <pwd.h> // getpwuid()
#include <grp.h> // getgrgid()
#include <time.h> // ctime()
int collect_filename(char *);
int collect(struct dirent *);
int print_filename();
void print(struct stat *); // 增加
void clear_filelist();
typedef struct FileList {
char *filename;
struct FileList *next;
} filelist;
filelist *head;
int bl = 1;
int bl_r = 1; // 增加 用于判断是否要输出 . 和 .. 文件信息
struct stat fileinfo;
enum {
ERROR_CODE_OK,
ERROR_CODE_GETCWD,
ERROR_CODE_OPEN,
ERROR_CODE_COLLECT_FILENAME,
ERROR_CODE_MALLOC,
ERROR_CODE_COLLECT,
ERROR_CODE_PRINT
};
int print_filename()
{
if(bl_r) {
// 输出 . 和 .. 文件信息
if (stat(".", &fileinfo) != 0) {
#ifdef TEST
printf("stat error!\n");
#endif
} else
print(&fileinfo);
printf(" .\n");
if (stat(".", &fileinfo) != 0) {
#ifdef TEST
printf("stat error!\n");
#endif
} else
print(&fileinfo);
printf(" ..\n");
}
filelist *ptr = head->next;
while (ptr != NULL) {
if (stat(ptr->filename, &fileinfo) != 0) {
#ifdef TEST
printf("stat error!\n");
#endif
continue;
}
print(&fileinfo);
printf(" %s\n", ptr->filename);
/* // 这些是我在写的过程中调试代码
printf("\t%lu", fileinfo.st_size);
printf("\t%lu", fileinfo.st_dev);
printf("\t%lu", fileinfo.st_ino);
printf("\t%u", fileinfo.st_uid);
printf("\t%lu", fileinfo.st_nlink);
printf("\n");
*/
ptr = ptr->next;
}
// printf("\n");
return ERROR_CODE_OK;
}
void print(struct stat *ptr)
{
if (S_ISREG(ptr->st_mode)) // 这个if-else语句是判断文件类型
putchar('-'); // 文件/文件夹/其他
else if (S_ISDIR(ptr->st_mode))
putchar('d'</