C语言模拟实现文件复制的操作

摘要:此为在Linux中采取程序设计来模拟实现系统中文件复制的操作,进一步了解Linux系统中的操作。

编写要求:

接着我们直接上代码吧!直接在里面解释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define LEN 512

int main(int argc,char** argv)
{ //以下为创建所需要使用的变量,fd为句柄,return为返回值,buf为缓冲区,tips用来存储输入。
int read_fd = -1;
int write_fd = -1;
int read_return = -1;
int write_return = -1;
char buf[LEN] = {0};
char tips[20] = {0};
int access_return = -1;
int stat_return = -1;
struct stat bs; //创建stat结构体

access_return = access(argv[1],F_OK | R_OK); //使用access函数来获取文件权限和存在状态。
if(access_return == 0)
read_fd = open(argv[1],O_RDONLY); //当返回值为0时执行读文件
else
{
printf("Open file error.\n"); //否则提示错误并退出
return 0;
}

memset(&bs, 0 , sizeof(bs)); //清空结构体

stat_return = stat(argv[1],&bs); //利用stat获取文件信息
access_return = access(argv[2],F_OK); //利用access获取第二个文件是否存在
if(access_return < 0)
{ //不存在则创建新文件
write_fd = open(argv[2],O_CREAT |O_RDWR,bs.st_mode);
if(write_fd < 0)
{ //如果创建失败则退出
close(read_fd);
close(access_return);
printf("Create file error.\n");
return 0;
}
}
else
{ //如果存在则询问是否重写
printf("Warning!Overwrite this file? yes/no?\n");
printf(" > ");
gets(tips);
if(strcmp(tips,"yes") == 0) //输入存入tips,如果为tips则重新
{
printf("reading...\n");
write_fd = open(argv[2],O_RDWR);
}
else
{ //如果输入不为tips则退出
close(read_fd);
close(access_return);
printf("Good bye!See you next time.\n");
return 0;
}
}

read_return = read(read_fd, buf, sizeof(buf)); //使用read读取文件内容
while( read_return > 0)
{
write_return = write(write_fd, buf, read_return); //使用write写入文件
if (write_return < read_return) //判断写入的字节是否小于读取的字节,小于则退出并提示写入失败
{
close(read_fd);
close(write_fd);
close(access_return);
printf("Write file error.\n");
return 0;
}
memset(buf, 0 ,sizeof(buf)); //清空buf缓冲区
read_return = read(read_fd, buf, sizeof(buf)); //再一次读取文件
}

//输出文件的大小
printf("It has been copied.This file size is %lld bytes.\n",bs.st_size);

//关闭各个句柄
close(access_return);
close(read_fd);
close(write_fd);
return 0;
}

大家可以参考Linux下文件读写的操作里面的函数解释~

------- 本文结束  感谢您的阅读 -------