在linux环境下,用C语言编写文件复制程序。分别使用系统调用read (fd,buf,nbytes)、write(fd, buf,nbytes)和文件的库函数fread(buf,size,nitems,fp)、fwrite(buf,size,nitems,fp),编写一个文件复制程序。
时间: 2024-02-03 11:15:51 浏览: 22
以下是使用系统调用read和write实现的文件复制程序:
```c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source> <destination>\n", argv[0]);
return 1;
}
int source_fd = open(argv[1], O_RDONLY);
if (source_fd == -1) {
perror("open");
return 2;
}
int dest_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dest_fd == -1) {
perror("open");
return 3;
}
char buffer[BUFFER_SIZE];
ssize_t nread;
while ((nread = read(source_fd, buffer, BUFFER_SIZE)) > 0) {
ssize_t nwritten = write(dest_fd, buffer, nread);
if (nwritten == -1) {
perror("write");
return 4;
}
}
if (nread == -1) {
perror("read");
return 5;
}
close(source_fd);
close(dest_fd);
return 0;
}
```
以下是使用文件的库函数fread和fwrite实现的文件复制程序:
```c
#include <stdio.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source> <destination>\n", argv[0]);
return 1;
}
FILE *source_fp = fopen(argv[1], "rb");
if (source_fp == NULL) {
perror("fopen");
return 2;
}
FILE *dest_fp = fopen(argv[2], "wb");
if (dest_fp == NULL) {
perror("fopen");
return 3;
}
char buffer[BUFFER_SIZE];
size_t nread;
while ((nread = fread(buffer, 1, BUFFER_SIZE, source_fp)) > 0) {
size_t nwritten = fwrite(buffer, 1, nread, dest_fp);
if (nwritten != nread) {
perror("fwrite");
return 4;
}
}
if (ferror(source_fp)) {
perror("fread");
return 5;
}
fclose(source_fp);
fclose(dest_fp);
return 0;
}
```
阅读全文