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