C语言文件——字符串的方式读出与写入

C语言文件——字符串的方式读出与写入

conclusion:

  • the steps of wirte into file
process
1.定义文件路径和文件操作
2.定义文件指针以及存储变量
3.打开文件(无出错处理)
4.读入所需的内容(输入-1代表结束)
5.关闭文件
  • the follow code you can validate above contents directly.
//C语言按字符串写入文件 
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxn 1024

int main(){
	//C语言按字符串写入文件 
	/* steps:
	1.定义文件路径和文件操作
	2.定义文件指针以及存储变量
	3.打开文件(无出错处理) 
	4.读入所需的内容(输入-1代表结束)
	5.关闭文件 
	*/
	//1.
	char *str=(char*)malloc(sizeof(char)*maxn);
	char *source="test2.txt";
	//2.
	char *op="w+t";
	FILE *fp=NULL;
	//3.
	fp=fopen(source,op);
	//4.
	puts("请输入信息:");
	while(1){
		if(strcmp(gets(str),"-1")==0) break;
		strcat(str,"\n");
		fputs(str,fp);
	} 
	if(ferror(fp)) puts("文件写入错误!");
	//5.
	fclose(fp);
	return 0;
}
  • the steps of read from file
process
1.定义文件路径和文件操作
2.定义文件指针以及存储变量
3.打开文件(出错处理)
4.读出文件的内容
5.关闭文件
  • hurry to make it come true by yourself and validate it !
  • follows are code
//C语言字符串读出或写入文件 
#include<stdio.h>
#include<stdlib.h>
#define maxn 1024

int main(){
	//读出文件 
	/* steps: 
	1.定义文件路径和文件操作
	2.定义文件指针以及存储变量
	3.打开文件(出错处理)
	4.读出文件的内容
	5.关闭文件 
	*/
	//1.
	char *str=(char*)malloc(sizeof(char)*maxn);
	char *source="test.txt";
	//2.
	char *op="r+t";
	FILE *fp=NULL;
	//3.
	fp=fopen(source,op);
	if(fp==NULL){
		puts("文件打开失败!");
		exit(0);
	}
	//4.
	while(fgets(str,maxn,fp)!=NULL){
		puts(str);
	}
	if(ferror(fp)) {
		puts("文件读取过程发生错误!");
	}
	//5.
	fclose(fp);
	return 0;
}
  • Please remember that every night you have stayied up and the path you have passed are always glittering !
    Cheer on ! The student who spare no effort on preparing for the examination for graduate school !
    2022/6/4
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

SweetCode

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

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

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

打赏作者

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

抵扣说明:

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

余额充值