linux ls的c代码,C++仿linux ls命令的实现代码

本文详细介绍了使用 C++ 编程语言实现 Linux 系统中 `ls` 命令的过程,包括读取目录、获取文件信息、判断文件类型并输出。代码展示了如何调用系统库函数进行文件操作,如 `opendir`、`readdir` 和 `lstat`,以及如何根据文件类型输出相应的符号。
摘要由CSDN通过智能技术生成

C++仿linux ls命令的实现代码

#include

#include

#include

#include

#include

#include

#include

#include

int count_file_size(const char *dirname);

unsigned long file_size = 0;

int main(int argc, char **argv)

{

count_file_size(argv[1]);

return 0;

}

int count_file_size(const char *dirname)

{

DIR *dp;

struct dirent *dirp;

struct stat buf;

char string[256];

int length = strlen(dirname);

bzero(string, 256);

snprintf(string, length + 1, "%s", dirname);

if ( (dp = opendir(dirname)) == NULL) {

fprintf(stderr, "Can't open dir %s\n", dirname);

exit(1);

}

while ( (dirp = readdir(dp) ) != NULL) {

if ( (strcmp(dirp->d_name, ".") == 0) || (strcmp(dirp->d_name, "..") == 0) )

continue;

#if 0

if (dirp->d_type == DT_DIR)

{

printf("%s\n", dirp->d_name);

continue;

}

#endif

snprintf(&string[length], strlen(dirp->d_name) + 1, "%s", dirp->d_name);

if (lstat(string, &buf) < 0) {

fprintf(stderr, "Get file stat falied: %s\n", strerror(errno));

continue;

}

if (S_ISREG(buf.st_mode))

printf("-");

else if (S_ISDIR(buf.st_mode))

printf("d");

else if (S_ISCHR(buf.st_mode))

printf("c");

else if (S_ISBLK(buf.st_mode))

printf("b");

else if (S_ISFIFO(buf.st_mode))

printf("p");

else if (S_ISLNK(buf.st_mode))

printf("l");

else if (S_ISSOCK(buf.st_mode))

printf("s");

else

continue;

printf("\t\t%-8lu\t\t%s\n", buf.st_size, dirp->d_name);

}

closedir(dp);

return 0;

}

开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C++仿linux ls命令的实现代码!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值