C语言文件——字符读出与写入
conclusion:
步骤 |
---|
1.定义文件源 |
2.fopen打开文件 |
3.fgetc读取文件(按照字符读取) |
4.当读取的内容不是EOF文件尾的时候,重复步骤 3 |
5.关闭文件 |
- the code to validate above contents
#include<stdio.h>
#include<stdlib.h>
int main() {
char ch;
char *source = "1.txt";
char *op = "r+t";
FILE *fp;
fp = fopen(source, op);
if (fp == NULL) {
puts("文件不存在!打开失败");
}
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
if (ferror(fp)) {
printf("文件读取错误!");
} else printf("读取成功!");
fclose(fp);
return 0;
}
步骤 |
---|
1.定义文件源 |
2.fopen打开文件 |
3.fputc写入字符到文件(按照字符写入) |
4.当读取的内容不是EOF文件尾的时候,重复步骤 3 |
5.关闭文件 |
- the code to validate above contents
#include<stdio.h>
#include<stdlib.h>
int main() {
char ch;
char *source = "1.txt";
char *op = "r+t";
FILE *fp;
char *source2 = "2.txt";
char *op2 = "a+t";
fp = fopen(source2, op2);
if (fp == NULL) printf("文件打开失败!");
printf("请输入一行字符:");
while ((ch = getchar()) != '\n') {
fputc(ch, fp);
}
if (ferror(fp)) printf("文件写入失败!");
else printf("文件写入成功!");
fclose(fp);
return 0;
}
- put on stream! 考研人!!!
2022/5/29