用C语言编写文件复制程序。分别使用系统调用read (fd,buf,nbytes)、write(fd, buf,nbytes)和文件的库函数fread(buf,size,nitems,fp)、fwrite(buf,size,nitems,fp),编写一个文件复制程序。
时间: 2024-02-05 14:12:03 浏览: 14
使用系统调用read和write实现文件复制程序的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define BUFFER_SIZE 4096
int main(int argc, char *argv[])
{
int source_fd, dest_fd, num_read, num_written;
char buffer[BUFFER_SIZE];
if (argc != 3) {
printf("Usage: %s source_file dest_file\n", argv[0]);
exit(EXIT_FAILURE);
}
source_fd = open(argv[1], O_RDONLY);
if (source_fd == -1) {
printf("Error opening source file\n");
exit(EXIT_FAILURE);
}
dest_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dest_fd == -1) {
printf("Error opening destination file\n");
close(source_fd);
exit(EXIT_FAILURE);
}
while ((num_read = read(source_fd, buffer, BUFFER_SIZE)) > 0) {
num_written = write(dest_fd, buffer, num_read);
if (num_written != num_read) {
printf("Error writing to destination file\n");
close(source_fd);
close(dest_fd);
exit(EXIT_FAILURE);
}
}
close(source_fd);
close(dest_fd);
return 0;
}
```
使用文件的库函数fread和fwrite实现文件复制程序的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 4096
int main(int argc, char *argv[])
{
FILE *source_fp, *dest_fp;
size_t num_read, num_written;
char buffer[BUFFER_SIZE];
if (argc != 3) {
printf("Usage: %s source_file dest_file\n", argv[0]);
exit(EXIT_FAILURE);
}
source_fp = fopen(argv[1], "rb");
if (source_fp == NULL) {
printf("Error opening source file\n");
exit(EXIT_FAILURE);
}
dest_fp = fopen(argv[2], "wb");
if (dest_fp == NULL) {
printf("Error opening destination file\n");
fclose(source_fp);
exit(EXIT_FAILURE);
}
while ((num_read = fread(buffer, 1, BUFFER_SIZE, source_fp)) > 0) {
num_written = fwrite(buffer, 1, num_read, dest_fp);
if (num_written != num_read) {
printf("Error writing to destination file\n");
fclose(source_fp);
fclose(dest_fp);
exit(EXIT_FAILURE);
}
}
fclose(source_fp);
fclose(dest_fp);
return 0;
}
```