linux编程基础黑马要点总结,黑马《linux基础编程》学习笔记(85到87)

八十五. 读取指定目录下的普通文件的个数——代码

getfilenummer.c

#include

#include

#include

#include

#include

int get_file_num(char* root)

{

int total = 0;

DIR* dir = NULL;

// 打开目录

dir = opendir(root);

// 循环从目录中读文件

char path[1024];

// 定义记录xiang指针

struct dirent* ptr = NULL;

while( (ptr = readdir(dir)) != NULL)

{

// 跳过. 和 ..

if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)

{

continue;

}

// 判断是不是目录

if(ptr->d_type == DT_DIR)

{

sprintf(path, "%s/%s", root, ptr->d_name);

// 递归读目录

total += get_file_num(path);

}

// 如果是普通文件

if(ptr->d_type == DT_REG)

{

total ++;

}

}

closedir(dir);

return total;

}

int main(int argc, char* argv[])

{

if(argc < 2)

{

printf("./a.out path");

exit(1);

}

int total = get_file_num(argv[1]);

printf("%s has regfile number: %d\n", argv[1], total);

return 0;

}

运行一下:

[root@VM_0_15_centos dir_op]# ls

chdir.c mkdir.c opendir.c readfileNum.c

[root@VM_0_15_centos dir_op]# gcc readfileNum.c

[root@VM_0_15_centos dir_op]# ./a.out

./a.out path[root@VM_0_15_centos dir_op]# ./a.out ./

./ has regfile number: 5

[root@VM_0_15_centos dir_op]# ./a.out /home

/home has regfile number: 6206

八十六. dup和dup2函数

af82651a42a813ca44694008626b809e.png

c4e7b4cd8446d6667e3a32636e2bae65.png

e822035fab7436bca55095263baa68c0.png

八十七. dup和dup2测试

22c4a1768cb34874c4c074c25d8af066.png

接下来看dup和dup2的例子

dup.c

#include

#include

#include

#include

#include

#include

#include

int main(void)

{

int fd = open("temp", O_RDWR | O_CREAT, 0664);

if(fd == -1)

{

perror("open");

exit(1);

}

// 复制文件描述符

//int fd2 = dup(fd);

int fd2 = fcntl(fd, F_DUPFD);

// 写文件

char* p = "让编程改变世界。。。。。。";

write(fd2, p, strlen(p));

close(fd2);

char buf[1024];

lseek(fd, 0, SEEK_SET);

read(fd, buf, sizeof(buf));

printf(" buf = %s\n", buf);

close(fd);

return 0;

}

dup2.c

#include

#include

#include

#include

#include

#include

#include

int main(void)

{

int fd = open("temp", O_RDWR | O_CREAT | O_APPEND, 0664);

if(fd == -1)

{

perror("open");

exit(1);

}

int fd2 = open("temp1", O_RDWR | O_CREAT | O_APPEND, 0664);

if(fd2 == -1)

{

perror("open open");

exit(1);

}

// 复制文件描述符

dup2(fd, fd2);

// 写文件

char* p = "change the world by programing。。。。。。";

write(fd2, p, strlen(p));

close(fd2);

char buf[1024];

lseek(fd, 0, SEEK_SET);

read(fd, buf, sizeof(buf));

printf(" buf = %s\n", buf);

close(fd);

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值