黑马《linux基础编程》学习笔记(85到87)

本文介绍了一个用于统计指定目录下普通文件数量的C程序,并提供了使用dup和dup2函数复制文件描述符的示例。代码展示了如何遍历目录、识别文件类型并递归地计数普通文件,同时演示了dup和dup2函数在文件描述符复制中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

getfilenummer.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>


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函数

 

 

 八十七. dup和dup2测试

 接下来看dup和dup2的例子

dup.c

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

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 <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

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;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值