linux中my_ls命令,在linux上完成自己的my_ls命令的编写(对dirent.h的研究)

用惯了,ls,想看看ls是如何实现的或者自己写一个自己的ls脚本命令。

偶然在c++沉思录上看到这个问题。关于dirent.h的库。

首先看看dirent是个什么gui,来自无所不知谷歌的解释

Dirent is an application programming interface (API) that enables programmers to list files and directories. Dirent API is commonly available in UNIX systems but not all compilers in Windows provide it. In particular, Microsoft Visual Studio lacks a dirent interface.

Thus, if you are porting software to Windows, you may find yourself rewriting code for Microsoft specific APIs. In order to reduce this work, I have create a clone of the dirent interface for Microsoft Visual Studio. The interface attempts to mimic the genuine UNIX API so that you could use the familiar UNIX data structures and function calls in both Windows and UNIX without modifying source code for one platform or the other.

还有一部分很详细的说明在万能wiki,连接 http://en.wikibooks.org/wiki/C_Programming/POSIX_Reference/dirent.h

先实践起来吧,一段源代码

* A simpler and shorter implementation of ls(1)

* ls(1) is very similar to the DIR command on DOS and Windows.

**************************************************************/

#include

#include

int listdir(const char *path) {

struct dirent *entry;

DIR *dp;

dp = opendir(path);

if (dp == NULL) {

perror("opendir");

return -1;

}

while((entry = readdir(dp)))

puts(entry->d_name);

closedir(dp);

return 0;

}

int main(int argc, char **argv) {

int counter = 1;

if (argc == 1)

listdir(".");

while (++counter <= argc) {

printf("\nListing %s...\n", argv[counter-1]);

listdir(argv[counter-1]);

}

return 0;

}

gcc dirent.c -o dirent

然后编写shell脚本

cat > myls

#! bin/sh

./home/gff/cplusplus/dirent/dirent

在home目录下兴建bin文件夹,将此文件夹加入到环境变量中

export PATH=$PATH:$home/bin

ok

实验一下

mkdir test

cd test

cat > a.txt

ctrl d

mkdir box

cd box

cat >b.txt

ctrl d

cd ../

基本目录已经完成

gff@ubuntu:~/test$ls

a.txt box

这是系统ls,只能显示一级目录

看看myls

gff@ubuntu:~/test$myls

..

.

box

a.txt

可以达到同样的效果

下面对于dirent明天再研究吧。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值