4. 利用标准I/O操作中的fopen、fread、fwrite、fseek、fclose等函数实现文件显示命令cat
时间: 2023-12-04 17:06:12 浏览: 85
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *fp;
char ch;
if (argc != 2) {
printf("Usage: %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("Error: cannot open file %s\n", argv[1]);
exit(EXIT_FAILURE);
}
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
return 0;
}
相关问题
4. 利用标准I/O操作中的fopen、fread、fwrite、fseek、fclose等函数实现文件显示命令cat和cp的功能。
1. cat命令实现:
```c++
#include <iostream>
#include <cstdio>
int main(int argc, char* argv[]) {
FILE* fp;
char buffer[1024];
if (argc < 2) {
std::cout << "Usage: cat <filename>" << std::endl;
return 1;
}
fp = fopen(argv[1], "r");
if (fp == nullptr) {
std::cout << "Error opening file" << std::endl;
return 1;
}
while (fgets(buffer, 1024, fp)) {
std::cout << buffer;
}
fclose(fp);
return 0;
}
```
2. cp命令实现:
```c++
#include <cstdio>
int main(int argc, char* argv[]) {
FILE* source;
FILE* destination;
char buffer[1024];
size_t count;
if (argc < 3) {
printf("Usage: cp <source> <destination>\n");
return 1;
}
source = fopen(argv[1], "rb");
if (source == nullptr) {
printf("Error opening source file\n");
return 1;
}
destination = fopen(argv[2], "wb");
if (destination == nullptr) {
printf("Error opening destination file\n");
fclose(source);
return 1;
}
while ((count = fread(buffer, 1, 1024, source))) {
fwrite(buffer, 1, count, destination);
}
fclose(source);
fclose(destination);
return 0;
}
```
. 利用标准I/O操作中的fopen、fread、fwrite、fseek、fclose等函数实现文件显示命令cat和 文件复制cp的功能。
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;
}
```
阅读全文