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