文件IO的opendir、readdir相关认识及运用

思维导图:

预习 opendir 和 readdir函数

opendir函数:

DIR *opendir(const char *name);

参数name:要打开的目录名

返回值:成功返回指向DIR结构体的指针,失败返回NULL

readdir函数:

struct dirent *readdir(DIR *dirp);

参数dirp:opendir () 函数的返回值

返回值:函数调用成功,返回读到的文件的信息,目录文件被读完了或者函数调用失败返回 NULL 函数返回值 struct dirent 结构体原型如下:
struct dirent {
               ino_t          d_ino;       /* Inode number */
               off_t          d_off;       /* Not an offset; see below */
               unsigned short d_reclen;    /* Length of this record */
               unsigned char  d_type;      /* Type of file; not supported
                                              by all filesystem types */
               char           d_name[256]; /* Null-terminated filename */
           };
DT_BLK      This is a block device.
DT_CHR      This is a character device.
DT_DIR      This is a directory.
DT_FIFO     This is a named pipe (FIFO).
DT_LNK      This is a symbolic link.
DT_REG      This is a regular file.
DT_SOCK     This is a UNIX domain socket.
DT_UNKNOWN  The file type could not be determined.

通过 opendir、readdir、write、read函数实现拷贝一个文件夹中的所有文件的功能(不考虑文件夹中还有文件夹的情况)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>

typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;

int main(int argc, const char *argv[])
{
	if(access(argv[2],F_OK) == -1)//判断目标文件夹是否存在
	{
		mkdir(argv[2],0777);//不存在则创建目标文件夹
	}else//如果存在,则需要判断该文件是否为目录文件
	{
		struct stat buf={0};
		stat(argv[2],&buf);
		mode_t mode=buf.st_mode;
		if(S_ISDIR(mode) != 1)
		{
			fprintf(stderr,"该文件不是一个目录文件!\n");
			return 1;
		}
	}
	DIR* df=opendir(argv[1]);
	if(dp == NULL)
	{
		perror("opendir");
		return 1;
	}
	while(1)
	{
		struct dirent* dt=readdir(df);
		if(dt == NULL)
		{
			break;
		}
		if(strcmp(dt->d_name,".")==0 || strcmp(dt->d_name,"..")==0)
		{
			continue;
		}
		chdir(argv[1]);//把工作目录切换到argv[1]里面
		int rfd=open(dt->d_name,O_RDONLY);
		if(rfd == -1)
		{
			perror("ropen");
		}
		chdir("..");//把工作目录切换到上一级目录
		chdir(argv[2]);
		int wfd=open(dt->d_name,O_WRONLY | O_CREAT | O_TRUNC,0666);
		if(wfd == -1)
		{
			perror("wopen");
		}
		chdir("..");
		while(1)
		{
			char s[16]={0};
			int res=read(rfp,s,15);
			if(res == 0)
			{
				breaak;
			}
			write(wfp,s,strlen(buf));
		}
	}
	close(rfp);
	close(wfp);
	closedir(df);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值