列出一个目录中的所有文件
2016-07-26 23:25
316 查看
#include "apue.h"
#include <dirent.h>
#include <errno.h>
#include <stdarg.h>
/*
* print a message and return to caller.
* Caller specifies "errnoflag"
*/
static void err_doit(int errnoflag,int error,const char *fmt, va_list ap)
{
char buf[MAXLINE];
vsnprintf(buf, MAXLINE, fmt, ap);
if(errnoflag)
snprintf(buf+strlen(buf),MAXLINE-strlen(buf),": %s",strerror(error));
strcat(buf, "\n");
fflush(stdout); /* in case stdout and stderr are the same */
fputs(buf,stderr);
fflush(NULL); /* flushes all stdio output streams */
}
/*
* Fatal error related to a system call
* Print a message and terminate.
*/
void err_sys(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(1,errno,fmt,ap);
va_end(ap);
exit(1);
}
/*
* Fatal error unrelated to a system call
* print a message and terminate.
*/
void err_quit(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(0,0,fmt,ap);
va_end(ap);
exit(0);
}
int main(int argc,char *argv[])
{
DIR *dp;
struct dirent *dirp;
if(argc != 2)
err_quit("usage: ls directory_name");
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);
}
#include <dirent.h>
#include <errno.h>
#include <stdarg.h>
/*
* print a message and return to caller.
* Caller specifies "errnoflag"
*/
static void err_doit(int errnoflag,int error,const char *fmt, va_list ap)
{
char buf[MAXLINE];
vsnprintf(buf, MAXLINE, fmt, ap);
if(errnoflag)
snprintf(buf+strlen(buf),MAXLINE-strlen(buf),": %s",strerror(error));
strcat(buf, "\n");
fflush(stdout); /* in case stdout and stderr are the same */
fputs(buf,stderr);
fflush(NULL); /* flushes all stdio output streams */
}
/*
* Fatal error related to a system call
* Print a message and terminate.
*/
void err_sys(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(1,errno,fmt,ap);
va_end(ap);
exit(1);
}
/*
* Fatal error unrelated to a system call
* print a message and terminate.
*/
void err_quit(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(0,0,fmt,ap);
va_end(ap);
exit(0);
}
int main(int argc,char *argv[])
{
DIR *dp;
struct dirent *dirp;
if(argc != 2)
err_quit("usage: ls directory_name");
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);
}
相关文章推荐
- OpenJ_POJ C16D Extracurricular Sports 找规律、大整数类
- 夏季集训前序
- Java中This ,Static,对象,对象的引用 等关键字的理解
- java中int和Integer的相互转化
- 关于MessageBox消息弹出框的制作
- hdu 2108
- 声场模型如何区分近场和远场
- Linux操作系统中JDK的安装
- HDU 3368 Reversi (暴力,DFS)
- Android Glide图片加载库的使用
- ServletInputStream的重复读取(多次读取)(转)
- BaseAdapter的使用及优化
- python获取系统硬件信息
- java编程---3.1 (关于String的练习题) 将字符串中的字符按需求等分,例如:把aqzxswerdcvfr变成AQZX-SWER-DCVF-R
- 对区域的操作
- 进程间通信(IPC)(2)—— 消息队列
- php基础部分总结篇-魔术方法
- 一些 Windows 系统不常见的 鼠标光标常数
- Python BeautifulSoup中文乱码问题的2种解决方法
- link、unlink、remove和rename