实验七:文件系统拷贝功能模拟 用C语言编写文件复制程序。分别使用系统调用read (fd,buf,nbytes)、write(fd, buf,nbytes)和文件的库函数fread(buf,size,nitems,fp)、fwrite(buf,size,nitems,fp),编写一个文件复制程序。
时间: 2024-02-03 10:15:24 浏览: 126
以下是一个使用系统调用的文件复制程序示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFFER_SIZE 4096
int main(int argc, char *argv[]) {
int input_fd, output_fd, bytes_read, bytes_written;
char buffer[BUFFER_SIZE];
if (argc != 3) {
printf("Usage: %s <input_file> <output_file>\n", argv[0]);
exit(EXIT_FAILURE);
}
input_fd = open(argv[1], O_RDONLY);
if (input_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
output_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (output_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
while ((bytes_read = read(input_fd, buffer, BUFFER_SIZE)) > 0) {
bytes_written = write(output_fd, buffer, bytes_read);
if (bytes_written != bytes_read) {
perror("write");
exit(EXIT_FAILURE);
}
}
if (bytes_read == -1) {
perror("read");
exit(EXIT_FAILURE);
}
if (close(input_fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
if (close(output_fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
return 0;
}
```
以下是一个使用文件的库函数的文件复制程序示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 4096
int main(int argc, char *argv[]) {
FILE *input_file, *output_file;
char buffer[BUFFER_SIZE];
size_t bytes_read, bytes_written;
if (argc != 3) {
printf("Usage: %s <input_file> <output_file>\n", argv[0]);
exit(EXIT_FAILURE);
}
input_file = fopen(argv[1], "rb");
if (input_file == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
output_file = fopen(argv[2], "wb");
if (output_file == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, input_file)) > 0) {
bytes_written = fwrite(buffer, 1, bytes_read, output_file);
if (bytes_written != bytes_read) {
perror("fwrite");
exit(EXIT_FAILURE);
}
}
if (ferror(input_file)) {
perror("fread");
exit(EXIT_FAILURE);
}
if (fclose(input_file) != 0) {
perror("fclose");
exit(EXIT_FAILURE);
}
if (fclose(output_file) != 0) {
perror("fclose");
exit(EXIT_FAILURE);
}
return 0;
}
```
阅读全文