使用readdir来将目录中的链接文件显示出来,并写入到一个文件内部,再将文件中的内容显示到屏幕上
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
int main(int argc, const char *argv[])
{
DIR *dp;
struct dirent *dt;
int FileNum = 0 ;
// FILE *fp = NULL;
FILE *fp_out = NULL;
char ch ;
// size_t res = 0 ;
fp_out = fopen(argv[2],"w+");
if(fp_out == NULL)
{
perror("Fail to fp_out");
}
dp = opendir(argv[1]);
if(dp == NULL)
{
perror("Fail to opendir");
return -1;
}
while(1)
{
dt = readdir(dp);
if(dt == NULL)
{
break;
}
if(dt->d_type == DT_LNK )
{
fprintf(fp_out,"%s \n",dt->d_name);
/* if((res = fread(ch,1,sizeof(ch),dt->d_name)) == 0)
{
break;
}
fwrite(ch,1,res,fp_out);
*/
FileNum++;
printf("第%d个链接文件: %s\n",FileNum,dt->d_name);
}
}
fseek(fp_out,0,SEEK_SET);
// long size = ftell(fp_out);
// printf("%ld\n",size);
while(fscanf(fp_out,"%c",&ch) != EOF)
{
printf("%c",ch);
ch = 0;
}
/*
while(1)
{
memset(ch,0,sizeof(ch));
n = read()
fp_out = fopen(argv[1],"w");
if(fp == NULL)
{
perror("Fail to fopen");
return -1;
}
}
*/
fclose(fp_out);
if(closedir(dp) < 0)
{
perror("Fail to closedir");
return -1;
}
printf("总文件个数: %d\n",FileNum);
return 0;
}
运行结果
写入的文件的内容