在C语言中,你可以使用标准库中的文件操作函数来实现文件的拷贝。下面是一个简单的示例代码,展示了如何使用`fopen`、`fread`和`fwrite`函数来拷贝一个文件:
```c
include include define BUFFER_SIZE 1024 int main() { FILE *source_file, *destination_file; char *buffer; size_t read_bytes, write_bytes; // 打开源文件用于读取 source_file = fopen("source.txt", "rb"); if (source_file == NULL) { perror("Error opening source file"); return -1; } // 打开目标文件用于写入 destination_file = fopen("destination.txt", "wb"); if (destination_file == NULL) { perror("Error opening destination file"); fclose(source_file); return -1; } // 分配内存用于缓冲区 buffer = (char*)malloc(BUFFER_SIZE); if (buffer == NULL) { perror("Memory allocation failed"); fclose(source_file); fclose(destination_file); return -1; } // 循环读取源文件并写入目标文件 while ((read_bytes = fread(buffer, 1, BUFFER_SIZE, source_file)) > 0) { write_bytes = fwrite(buffer, 1, read_bytes, destination_file); if (write_bytes != read_bytes) { perror("Error writing to destination file"); free(buffer); fclose(source_file); fclose(destination_file); return -1; } } // 检查是否读取过程中出现错误 if (ferror(source_file)) { perror("Error reading source file"); free(buffer); fclose(source_file); fclose(destination_file); return -1; } // 释放缓冲区内存 free(buffer); // 关闭文件 fclose(source_file); fclose(destination_file); printf("File copied successfully.\n"); return 0; } ``` 这段代码首先定义了缓冲区大小,然后打开源文件和目标文件。接着,它分配了一个缓冲区来存储从源文件读取的数据,并使用`fread`函数读取数据。读取的数据随后使用`fwrite`函数写入目标文件。这个过程会一直持续,直到`fread`返回0,表示源文件已经读取完毕。最后,代码检查是否有任何错误发生,并在完成后关闭文件。 请确保将`source.txt`和`destination.txt`替换为你想要拷贝的文件的实际路径。此外,这段代码假设源文件存在且可读,目标文件可写。在实际应用中,你可能需要添加更多的错误检查和处理逻辑。