作业:使用readdir来将目录中的链接文件显示出来,并写入到一个文件内部,再将文件中的内容显示到屏幕上
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<dirent.h>
#include<unistd.h>
#include<fcntl.h>
int main(int argc, const char *argv[])
{
DIR *dp;
struct dirent *dt;
int filenum=0;
FILE *fp=fopen(argv[2],"w");
if(NULL==fp)
{
perror("file to open");
return -1;
}
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==DT_LNK)
{
printf("%s\n",dt->d_name);
fprintf(fp,"%s\n",dt->d_name);
filenum++;
}
}
printf("共有链接文件:%d个\n",filenum);
fclose(fp);
fp=fopen(argv[2],"r");
if(NULL==fp)
{
perror("file to open");
return -1;
}
char buf[100];
printf("写入的文件名:\n");
while(fgets(buf,100,fp)!=NULL)
{
fputs(buf,stdout);
}
fclose(fp);
if(closedir(dp)<0)
{
perror("fail to closedir");
return -1;
}
return 0;
}