2、编写一个简单的文件复制程序,利用程序执行参数指定源文件名和目的文件名,如: ./copy source.jpg destiny.jpg int main(int argc, char *argv) argv[1] argv[2] 即在执行时将源文件source.jpg复制到文件destiny.jpg中。打开其中任一文件时应有相应报错显示并退出
时间: 2024-03-10 12:46:25 浏览: 25
以下是一个简单的文件复制程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <source_file> <dest_file>\n", argv[0]);
exit(1);
}
FILE *source_file = fopen(argv[1], "rb");
if (source_file == NULL) {
perror("Error opening source file");
exit(1);
}
FILE *dest_file = fopen(argv[2], "wb");
if (dest_file == NULL) {
perror("Error opening destination file");
fclose(source_file);
exit(1);
}
char buffer[BUFFER_SIZE];
size_t size;
while ((size = fread(buffer, 1, BUFFER_SIZE, source_file)) > 0) {
if (fwrite(buffer, 1, size, dest_file) != size) {
perror("Error writing to destination file");
fclose(source_file);
fclose(dest_file);
exit(1);
}
}
fclose(source_file);
fclose(dest_file);
printf("File copied successfully.\n");
return 0;
}
```
代码中使用了两个文件指针:source_file和dest_file,分别表示源文件和目标文件。首先,程序检查是否传入了正确的参数数量,如果不是,则输出使用说明并退出。然后,程序尝试打开源文件和目标文件,如果打开失败,则输出错误信息并退出。接下来,程序使用一个循环来读取源文件中的数据,并将其写入目标文件中。最后,程序关闭两个文件指针,并输出复制成功的信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)