c语言编写一个程序来创建给定文件的副本。文件名在命令行中指定。 输入格式
时间: 2024-09-24 22:18:09 浏览: 55
在C语言中,你可以使用标准库函数如`fopen()`, `fclose()`, 和 `fread()` 来读取源文件的内容,然后使用`fwrite()`函数将内容写入新的副本文件。以下是一个简单的示例程序,它接受命令行参数作为源文件名和目标文件名:
```c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
// 检查命令行参数的数量
if (argc != 3) {
printf("Usage: %s <source_file> <destination_file>\n", argv[0]);
return 1;
}
const char *src_filename = argv[1];
const char *dst_filename = argv[2];
// 打开源文件并检查打开是否成功
FILE *src_file = fopen(src_filename, "rb");
if (!src_file) {
perror("Failed to open source file");
return 1;
}
// 打开目标文件用于写入,如果不存在则创建
FILE *dst_file = fopen(dst_filename, "wb");
if (!dst_file) {
perror("Failed to create destination file");
fclose(src_file);
return 1;
}
// 读取源文件内容并写入目标文件
size_t bytes_read;
char buffer[4096]; // 可调整大小以适应文件大小
while ((bytes_read = fread(buffer, sizeof(char), sizeof(buffer), src_file)) > 0) {
fwrite(buffer, sizeof(char), bytes_read, dst_file);
}
// 关闭文件
fclose(src_file);
fclose(dst_file);
printf("Copied %s to %s successfully.\n", src_filename, dst_filename);
return 0;
}
```
要运行此程序,你需要提供两个参数,例如在命令行中输入:
```sh
./copy_file src.txt dest.txt
```
阅读全文
相关推荐


















