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

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

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

扫描二维码关注公众号,回复: 4586540 查看本文章
#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;
}

猜你喜欢

转载自blog.csdn.net/garrulousabyss/article/details/85149697