用惯了,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明天再研究吧。。