1、判断文件是否是目录文件
任务描述:
- 给出一个文件的绝对路径,判断该文件是否是目录文件
- 将文件的绝对路径做输入参数,打印信息表明该文件是否为目录
相关知识:
-
S_ISDIR (st_mode) :判断是否为目录
main.c:
#include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<unistd.h> #include<stdlib.h> struct stat buf; int main(int argc ,char *argv[]) { if(argc!=2){ perror("argc error "); exit(1); } if(stat(argv[1],&buf)!=0){ perror("stat error "); exit(1); } if(S_ISDIR(buf.st_mode)) printf("it id a dir "); else printf("it isn't a dir "); return 0; }
2、列出指定目录下所有文件名
任务描述:
- 绝对路径名做输入参数,打印出该路径下所有文件名
相关知识:
-
DIR* opendir (const char * path )
opendir()用来打开参数name 指定的目录, 并返回DIR*形态的目录流, 和open()类似, 接下来对目录的读取和搜索都要使用此返回值。返回值:成功则返回DIR* 型态的目录流, 打开失败则返回NULL。不用管DIR的内部结构是什么样的,只要知道要传给readdir()函数的参数就行了。
-
struct dirent *readdir(DIR *dir):读取目录
它的参数是opendir函数返回的DIR*句柄,而该函数的返回值是struct dirent* 类型,这个结构体定义如下:
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file */
char d_name[256]; /* filename */
};
d_name存放的是文件的名字。
Readdir返回指向下一个目录项的指针。
main.c:
#include<stdio.h> #include<sys/types.h> #include<unistd.h> #include<stdlib.h> #include<dirent.h> struct dirent *entry; int main(int argc ,char *argv[]) { char path[1024]; DIR *dirptr=NULL; if(argc!=2){ perror("argc error "); exit(1); } if((dirptr=opendir(argv[1]))==NULL){ perror("stat error "); exit(1); } else{ while(entry=readdir(dirptr)){ if(strcmp(entry->d_name,".")==0||strcmp(entry->d_name,"..")==0) continue;//如果输入的是相对路径,不处理 //sprintf(path,"%s/%s",argv[1],entry->d_name);//输出绝对路径 printf("%s ",entry->d_name); } closedir(dirptr); } return 0; }
3、列出指定目录下所有文件的绝对路径
相关知识:
-
绝对路径由指定目录的绝对路径加上文件的相对路径得到
-
int sprintf( char *buffer, const char *format, [ argument] … ):字符串格式化命令,主要功能是把格式化的数据写入某个字符串中
buffer:char型指针,指向将要写入的字符串的缓冲区。
format:格式化字符串。
[argument]...:可选参数,可以是任何类型的数据。
返回值:字符串长度(strlen)
main.c:
#include<stdio.h> #include<sys/types.h> #include<unistd.h> #include<stdlib.h> #include<dirent.h> #include<string.h> #define N 1024 struct dirent *entry; int main(void) { DIR *dirptr=NULL; char name[N]; char buf[N]; char path[N]; printf("please input a path "); fgets(name,N,stdin);//输入路径 int i=strlen(name); name[i-1]='