打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
03

文件

  • ascii 字符处理



FILE结构定义说明

struct   _iobuf   {      char   *_ptr;           	//文件输入的下一个位置      int    _cnt;          		//当前缓冲区的相对位置      char   *_base;         	//指基础位置(应该是文件的其始位置)      int    _flag;       	  	//文件标志      int    _file;         		//文件的有效性验证      int    _charbuf;   		//检查缓冲区状况,如果无缓冲区则不读取      int    _bufsiz;     		//文件的大小      char   *_tmpfname;	//临时文件名 };typedef   struct   _iobuf   FILE; 


文件打开方式

r: 文件已存在,只能从该文件读出;

w: 不存在则新建,已存在则删旧建新;

a: 已存在文件追加信息;



fopen打开文件出错,返回空指针值NULL;

#include <stdio.h>#include <stdlib.h>/* run this program using the console pauser or add your own getch, system("pause") or input loop */int main(int argc, char *argv[]) {		FILE *fp;	if(!(fp = fopen("D:\\fishc.txt","rb")))  //b->二进制  	{		printf("Can not open D:\\fishc file\n");		system("pause");	}	else	{		printf("Open success!\n");	}		return 0;}


fclose()

  • 成功返回0,否则返回EOF(-1)

  • 文件脱钩,指针不再指向该文件;

#include <stdio.h>#include <stdlib.h>/* run this program using the console pauser or add your own getch, system("pause") or input loop */int main(int argc, char *argv[]) {		FILE *fp;	char ch,filename[20] ;	printf("Please input the filename you want to write:\t");	scanf("%s",filename);		if(!(fp = fopen(filename,"wt ")))  // 打开文本文件,允许读和写; 	{		printf("Can not open D:\\fishc file\n");		exit(0);	//终止程序 	}		printf("\nPlease input the sentences you want to write:\t") ;		ch = getchar();			//so到底为啥要搞两个ch = getchar()? #多了一个空行	ch = getchar();	while( ch != EOF)  		//ctrl z 	{		fputc(ch,fp);		ch = getchar();	}		fclose(fp);			return 0;}


fgetc()

ch = fgetc(fp)

打开文件fp,读取一个字符并送入ch中;

  • 只允许读/读写方式打开

  • 位置指针,只想当前读写字节;

  • 可以连续多次使用,读取多个字节;

文件指针、文件内部位置指针

#include <stdio.h>#include <stdlib.h>/* run this program using the console pauser or add your own getch, system("pause") or input loop */int main(int argc, char *argv[]) {		FILE *fp;	char ch,filename[20] ;	printf("Please input the filename you want to write:\t");	scanf("%s",filename);		if(!(fp = fopen(filename,"r")))  // 打开文本文件,允许读和写; 	{		printf("Can not open D:\\fishc file\n");		exit(0);	//终止程序 	}		while( ch != EOF)  		//ctrl z 	{		ch = fgetc(fp);		putchar(ch);	}		fclose(fp);			return 0;}

字符流向:file->ch->putchar(printer)

EOF == -1

feof(fp) 二进制文件顺序读入字符终结标志;返回1为结束;


来源:https://www.icode9.com/content-4-668601.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
教你彻底学会c语言基础——文件操作
C语言文件操作详解
【C语言】文件常用读写操作(含读取学生信息示例)
[转]c/c++文件操作-研途小憩-中国教育人博客
《C语言程序设计(第2版)》第12章文件
C语言详解——文件读取
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服