ls -al命令的简单实现(C语言版)

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'</
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值