linux下使用系统调用编程实现dir命令功能 -- 完整篇

本文介绍了一个使用C语言编写的程序,该程序可以遍历指定目录及其子目录下的所有文件,并显示每个文件的详细信息,包括文件大小、最后修改时间和是否为目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://dev.csdn.net/article/36/36598.shtm 之内容增强板

解决http://dev.csdn.net/article/36/36598.shtm 之中的问题,能够显示不同目录下的所有文件信息,不受到执行文件路径的限制。

 

/*
函数名: dir
功  能: dir命令
用  法: int dir(char *str1);
程序例:
*/
#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>

static int get_info(const char * filename,const char * path)
{
/*    printf("%s/n",filename);*/
    char   fullname[255];
    struct stat statbuf;
   
    if(!strcmp(filename,".")||!strcmp(filename,".."))return(0);
    strcpy(fullname,path);
    strcat(fullname,"/");
    strcat(fullname,filename);
    if(lstat(fullname,&statbuf)==-1)
    {
        printf("%s ,errno %d,%s/n",fullname,errno,strerror(errno ));
        return(1);
    }
    if(S_ISDIR(statbuf.st_mode))
        printf("%s/t Directory/tmodified at %s",fullname,ctime(&statbuf.st_mtime));
    if(S_ISREG(statbuf.st_mode))
        printf("%s/tsize:%ld bytes/tmodified at %s",fullname,statbuf.st_size,ctime(&statbuf.st_mtime));
 
    return(0);
}

int  main(int argc, char *argv[])

{
    DIR * dirp;
    struct dirent * direntp;
    char* path = "/home/zhuhj";

   if(argc>1)
   {
       path = argv[1];
       printf("file name is %s/n",path);
   }

    if((dirp=opendir(path)))
    {
        while((direntp=readdir(dirp))!=NULL)
            get_info(direntp->d_name,path);
        /* printf("%s/t",direntp->d_name);*/
        closedir(dirp);
        exit(1);
    }
    else
    {
        printf("Error/n");
        exit(1);
    }

    return(0);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值