当前位置:网站首页>C语言文件——字符串的方式读出与写入

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

2022-06-09 06:49:00 SweetCode

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
原网站

版权声明
本文为[SweetCode]所创,转载请带上原文链接,感谢
https://blog.csdn.net/ucjcklc/article/details/125126609