C语言文件——字符读出与写入

C语言文件——字符读出与写入

conclusion:

  • the steps of read file
步骤
1.定义文件源
2.fopen打开文件
3.fgetc读取文件(按照字符读取)
4.当读取的内容不是EOF文件尾的时候,重复步骤 3
5.关闭文件
  • the code to validate above contents
//字符读或写入文件
#include<stdio.h>
#include<stdlib.h>


int main() {
	//读出文件的内容并显示到屏幕
	/*
	   1.定义文件源
   	   2.fopen打开文件
	   3.fgetc读取文件(按照字符读取)
	   4.当读取的内容不是EOF文件尾的时候,重复步骤 3
	   5.关闭文件
	*/
	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;
}
  • the steps of input file
步骤
1.定义文件源
2.fopen打开文件
3.fputc写入字符到文件(按照字符写入)
4.当读取的内容不是EOF文件尾的时候,重复步骤 3
5.关闭文件
  • the code to validate above contents
//字符读或写入文件
#include<stdio.h>
#include<stdlib.h>


int main() {
	//以字符的方式将内容写入到指定的文件
	/*
		1.定义文件源
		2.fopen打开文件
		3.fputc写入字符到文件(按照字符写入)
		4.当读取的内容不是EOF文件尾的时候,重复步骤 3
		5.关闭文件
	*/

	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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SweetCode

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值