C语言文件——字符串的方式读出与写入
conclusion:
the steps of wirte into file
process 1.定义文件路径和文件操作 2.定义文件指针以及存储变量 3.打开文件(无出错处理) 4.读入所需的内容(输入-1代表结束) 5.关闭文件
the follow code you can validate above contents directly.
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# define maxn 1024
int main ( ) {
char * str= ( char * ) malloc ( sizeof ( char ) * maxn) ;
char * source= "test2.txt" ;
char * op= "w+t" ;
FILE * fp= NULL ;
fp= fopen ( source, op) ;
puts ( "请输入信息:" ) ;
while ( 1 ) {
if ( strcmp ( gets ( str) , "-1" ) == 0 ) break ;
strcat ( str, "\n" ) ;
fputs ( str, fp) ;
}
if ( ferror ( fp) ) puts ( "文件写入错误!" ) ;
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
# include <stdio.h>
# include <stdlib.h>
# define maxn 1024
int main ( ) {
char * str= ( char * ) malloc ( sizeof ( char ) * maxn) ;
char * source= "test.txt" ;
char * op= "r+t" ;
FILE * fp= NULL ;
fp= fopen ( source, op) ;
if ( fp== NULL ) {
puts ( "文件打开失败!" ) ;
exit ( 0 ) ;
}
while ( fgets ( str, maxn, fp) != NULL ) {
puts ( str) ;
}
if ( ferror ( fp) ) {
puts ( "文件读取过程发生错误!" ) ;
}
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