. 利用标准I/O操作中的fopen、fread、fwrite、fseek、fclose等函数实现文件显示命令cat和 文件复制cp的功能。
时间: 2024-05-15 19:19:35 浏览: 79
1. 文件显示命令cat的实现:
```c
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("Error opening file %s\n", argv[1]);
return 1;
}
char buffer[BUFSIZ];
size_t nread;
while ((nread = fread(buffer, 1, BUFSIZ, fp)) > 0) {
fwrite(buffer, 1, nread, stdout);
}
fclose(fp);
return 0;
}
```
2. 文件复制命令cp的实现:
```c
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <source> <destination>\n", argv[0]);
return 1;
}
FILE *src = fopen(argv[1], "rb");
if (src == NULL) {
printf("Error opening source file %s\n", argv[1]);
return 1;
}
FILE *dst = fopen(argv[2], "wb");
if (dst == NULL) {
printf("Error opening destination file %s\n", argv[2]);
fclose(src);
return 1;
}
char buffer[BUFSIZ];
size_t nread;
while ((nread = fread(buffer, 1, BUFSIZ, src)) > 0) {
fwrite(buffer, 1, nread, dst);
}
fclose(src);
fclose(dst);
return 0;
}
```
阅读全文