实现一个简单的ls命令
2010-01-25 20:36
447 查看
//myls.c
#include <stdio.h>
#include <dirent.h>
#include <stdarg.h>
#include <errno.h>
#define MAXLINE 4096 /* max line length */
static void
err_doit(int errnoflag, const char *fmt, va_list ap)
{
int errno_save;
char buf[MAXLINE];
errno_save = errno; /* value caller might want printed */
vsprintf(buf, fmt, ap);
if (errnoflag)
sprintf(buf+strlen(buf), ": %s", strerror(errno_save));
strcat(buf, "/n");
fflush(stdout); /* in case stdout and stderr are the same */
fputs(buf, stderr);
fflush(NULL); /* flushes all stdio output streams */
return;
}
void
err_sys(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(1, fmt, ap);
va_end(ap);
exit(1);
}
void
err_quit(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(0, fmt, ap);
va_end(ap);
exit(1);
}
int main(int argc,char *argv[])
{
DIR *dp;
struct dirent *dirp;
if(argc!=2)
err_quit("argument error!");
if((dp=opendir(argv[1]))==NULL)
err_sys("can't open %s",argv[1]);
while((dirp=readdir(dp))!=NULL)
printf("%s/n",dirp->d_name);
closedir(dp);
exit(0);
}
编译
$gcc -o myls myls.c
使用
$./myls [path]
#include <stdio.h>
#include <dirent.h>
#include <stdarg.h>
#include <errno.h>
#define MAXLINE 4096 /* max line length */
static void
err_doit(int errnoflag, const char *fmt, va_list ap)
{
int errno_save;
char buf[MAXLINE];
errno_save = errno; /* value caller might want printed */
vsprintf(buf, fmt, ap);
if (errnoflag)
sprintf(buf+strlen(buf), ": %s", strerror(errno_save));
strcat(buf, "/n");
fflush(stdout); /* in case stdout and stderr are the same */
fputs(buf, stderr);
fflush(NULL); /* flushes all stdio output streams */
return;
}
void
err_sys(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(1, fmt, ap);
va_end(ap);
exit(1);
}
void
err_quit(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(0, fmt, ap);
va_end(ap);
exit(1);
}
int main(int argc,char *argv[])
{
DIR *dp;
struct dirent *dirp;
if(argc!=2)
err_quit("argument error!");
if((dp=opendir(argv[1]))==NULL)
err_sys("can't open %s",argv[1]);
while((dirp=readdir(dp))!=NULL)
printf("%s/n",dirp->d_name);
closedir(dp);
exit(0);
}
编译
$gcc -o myls myls.c
使用
$./myls [path]
相关文章推荐
- 实现一个简单的ls命令
- unix ls命令的一个简单实现
- unix ls命令的一个简单实现
- 列出文件名和属性——实现一个简单的ls命令
- ls(1)命令的简单实现(一)
- Linux(Fedora)下ls命令的简单实现
- Linux下ls命令的简单实现
- linux入门:编写一个简单的shell(仅支持部分ls,ps命令)
- Linux下ls命令的简单模拟实现
- Linux C编程的一个小例子——实现一个简单的who命令(第一版)
- ls命令的简单实现
- Linux下之使用简单3种创建文件的命令,并实现一个Html和JavaScript小程序
- 使用pipe实现一个简单的类似tee命令的功能
- 使用linux-c编程实现简单的ls命令
- 一个简单的linux命令——ls
- Linux命令简单实现 -- ls
- 一个在终端实现类Linux shell(cd ls命令)UI界面的项目(C语言实现)
- 使用hadoop命令rcc生成Record 一个简单的方法来实现自己的定义writable对象
- 做linux第四次实验,看错实验要求,花了一个下午自己模拟着实现一个ls命令。。。。
- 使用EF6和MVC5实现一个简单的选课系统--EF6的弹性链接和命令拦截(4/12)