使用readdir来将目录中的链接文件显示出来,并写入到一个文件内部,再将文件中的内容显示到屏幕上
代码:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<dirent.h>
#include<string.h>
int main(int argc, const char *argv[])
{
DIR *dp;
struct dirent *dt;
int filenum=0;
FILE *fp=NULL;
if(argc !=3)
{
fprintf(stderr,"usage:%s filename\n",argv[0]);
return -1;
}
fp=fopen(argv[2],"w+");
dp=opendir(argv[1]);
if(NULL==dp)
{
perror("Fail to opendir");
return -1;
}
while(1)
{
dt=readdir(dp);
if(NULL==dt)
{
break;
}
if(dt->d_type ==10)
{
printf("%s\n",dt->d_name);
filenum++;
}
}
if(closedir(dp)<0)
{
perror("Fail to closedir");
return -1;
}
printf("filenum:%d\n",filenum);
fseek(fp,0,SEEK_SET);
char buf[1024]={0};
char *ch;
while(1)
{
memset(buf,0,sizeof(buf));
ch=fgets(buf,sizeof(buf),fp);
if(NULL==ch){
break;
}
fputs(buf,fp);
}
fclose(fp);
return 0;
}
运行结果: