文件
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为结束;
联系客服