目录操作函数:
DIR* opendir(char* name)
int closedir(DIR* dp)
struct dirent* readdir(DIR* dp);
struct dirent{
inode
char dname[256]
}
递归遍历目录:ls -R.c
1.判断命令行参数,获取用户要查询的目录名。 argv【1】
argc ==1 -->./
2.判断用户指定的是否是目录 stat S_ISDIR() -->封装函数 isFile
3.读目录
opendir(dir)
while(readdir()){
普通文件 ,直接打印
目录:
拼接目录访问绝对路径。 sprintf(path,“%s/%s”,dir,d._name)
递归调用自己 。 --》 opendir(path) readdir closedir
}
closedir()
// 实现 ls -R
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/stat.h>
#include<dirent.h>
void isFile(char*);
void read_dir(char* dir){
char path[256];
DIR* dp;
struct dirent* sdp;
dp = opendir(dir);
if(dp==NULL){
perror("opendir error");
return ;
}
while((sdp=readdir(dp))!=NULL){
if(strcmp(sdp->d_name,".")==0 || strcmp(sdp->d_name,"..")==0){
continue;
}
sprintf(path,"%s%s",dir,sdp->d_name);
isFile(path);
}
closedir(dp);
return;
}
void isFile(char* name){
int ret=0;
struct stat sb;
ret = stat(name,&sb);
if(ret==-1){
perror("stat error");
return;
}
if(S_ISDIR(sb.st_mode)){
read_dir(name);
}
printf("%s\n",name);
return;
}
int main(int argc,char* argv[]){
if(argc==1){
isFile("./");
}else{
isFile(argv[1]);
}
return 0;
dup和 dup2:
cat a.c > out 重定向
cat a.c >>out 追加写
int dup(int oldfd)
oldfd:已有文件描述符
返回:新文件描述符
int dup2(int oldfd, int newfd);
返回: 新的文件描述符
oldfd <---newfd
往newfd里写 相当于往 oddfd 对应的文件中写
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
int main(int argc,char* argv[]){
int fd1 = open(argv[1],O_RDWR);
int fd2 = open(argv[2],O_RDWR);
int fdret=dup2(fd1,fd2);//返回新的文件描述符fd2
printf("%d\n",fdret);
int ret=write(fd2,"123",3);//写入fd1指向的文件
dup2(fd1,STDOUT_FILENO);//奖屏幕输出,重定向给fd1所指向的文件
printf("-------?");
return 0;
}
fcntl 函数实现dup2:
int fcntl(int fd,int cmd, ....)
cmd : F_DUPFD
惨3: 被占用,返回最小未使用
未被占用,返回该描述符
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char* argv[]){
int fd1 = open(argv[1],O_RDWR);
printf("fd1=%d\n",fd1);
int newfd = fcntl(fd1,F_DUPFD,0);//0被占用 ,fcntl使用文件描述符表中最小文件描述符返回4
printf("newfd = %d\n",newfd);
int newfd2 = fcntl(fd1,F_DUPFD,7);//指定7未被占用 返回》=7的描述符
printf("newfd2 = %d\n",newfd2);
int ret = write(newfd2,"yyyyy",5);//写入 fd1中
printf("%d\n",ret);
return 0;
}