linux写一个有cp功能的c文件
时间: 2024-02-13 16:04:16 浏览: 61
下面是一个简单的实现 cp 功能的 C 语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define BUF_SIZE 4096
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <source_file> <destination_file>\n", argv[0]);
exit(EXIT_FAILURE);
}
FILE *src_file = fopen(argv[1], "rb");
if (src_file == NULL) {
printf("Failed to open source file %s\n", argv[1]);
exit(EXIT_FAILURE);
}
FILE *dest_file = fopen(argv[2], "wb");
if (dest_file == NULL) {
printf("Failed to open destination file %s\n", argv[2]);
fclose(src_file);
exit(EXIT_FAILURE);
}
char buffer[BUF_SIZE];
size_t nread;
while ((nread = fread(buffer, 1, BUF_SIZE, src_file)) > 0) {
fwrite(buffer, 1, nread, dest_file);
}
fclose(src_file);
fclose(dest_file);
return 0;
}
```
这个程序会将 `argv[1]` 指定的源文件复制到 `argv[2]` 指定的目标文件中。它会一次读取 `BUF_SIZE` 个字节,然后将它们写入目标文件中。如果源文件读取结束,则程序会退出。
阅读全文