用C语言编写文件复制程序。分别使用系统调用read (fd,buf,nbytes)、write(fd, buf,nbytes)和文件的库函数fread(buf,size,nitems,fp)、fwrite(buf,size,nitems,fp),编写一个文件复制程序。
时间: 2024-02-03 15:14:56 浏览: 53
利用汇编写的文件操作小程序,功能是复制文件
使用系统调用read和write实现文件复制程序:
```c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
int source_fd, target_fd;
ssize_t nread;
char buf[BUF_SIZE];
if (argc != 3) {
fprintf(stderr, "Usage: %s source_file target_file\n", argv[0]);
return 1;
}
source_fd = open(argv[1], O_RDONLY);
if (source_fd == -1) {
perror("open");
return 1;
}
target_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (target_fd == -1) {
perror("open");
return 1;
}
while ((nread = read(source_fd, buf, BUF_SIZE)) > 0) {
if (write(target_fd, buf, nread) != nread) {
perror("write");
return 1;
}
}
if (nread == -1) {
perror("read");
return 1;
}
if (close(source_fd) == -1) {
perror("close");
return 1;
}
if (close(target_fd) == -1) {
perror("close");
return 1;
}
return 0;
}
```
使用文件的库函数fread和fwrite实现文件复制程序:
```c
#include <stdio.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
FILE *source_fp, *target_fp;
size_t nread;
char buf[BUF_SIZE];
if (argc != 3) {
fprintf(stderr, "Usage: %s source_file target_file\n", argv[0]);
return 1;
}
source_fp = fopen(argv[1], "rb");
if (source_fp == NULL) {
perror("fopen");
return 1;
}
target_fp = fopen(argv[2], "wb");
if (target_fp == NULL) {
perror("fopen");
return 1;
}
while ((nread = fread(buf, 1, BUF_SIZE, source_fp)) > 0) {
if (fwrite(buf, 1, nread, target_fp) != nread) {
perror("fwrite");
return 1;
}
}
if (ferror(source_fp)) {
perror("fread");
return 1;
}
if (fclose(source_fp) != 0) {
perror("fclose");
return 1;
}
if (fclose(target_fp) != 0) {
perror("fclose");
return 1;
}
return 0;
}
```
阅读全文