#include<stdio.h>#include<stdlib.h>intmain(){
FILE* fp =fopen("test.txt","r");//以只读的形式打开文件。if(fp ==NULL)//判断是否成功打开文件。{printf("Can't open the file.\n");exit(0);}fclose(fp);//关闭已打开的文件。
fp =NULL;return0;}
读取字符 int fgetc ( FILE * stream ); fgetc读取成功会返回读取的元素,在读取失败的时候会返回EOF。
#include<stdio.h>#include<stdlib.h>intmain(){
FILE* fp =fopen("test.txt","rb");//以二进制的方式打开文件char ch;if(fp ==NULL){printf("Can't open the file.\n");exit(0);}do{
ch =fgetc(fp);//读取字符printf("%c", ch);}while(ch !=EOF);fclose(fp);
fp =NULL;return0;}
写入字符 int fputc ( int character, FILE * stream ); fputc读取成功会返回读取的元素,在读取失败的时候会返回EOF。
#include<stdio.h>#include<stdlib.h>intmain(){
FILE* fp =fopen("test.txt","wb");char* p ="asdfgh";if(fp ==NULL){printf("Can't open the file.\n");exit(0);}do{fputc(*p, fp);//输出字符
p++;}while(*p !='\0');fputc(*p, fp);fclose(fp);
fp =NULL;return0;}
#include<stdio.h>#include<stdlib.h>intmain(){
FILE* fp =fopen("test.txt","rb");char* p =(char*)malloc(20);if(fp ==NULL){printf("Can't open the file.\n");exit(0);}fread(p,sizeof(char),20, fp);//从fp只想文件中读取20个类型为char的元素放入p指向的空间里。printf("%s\n", p);fclose(fp);
fp =NULL;return0;}
#include<stdio.h>#include<stdlib.h>intmain(){
FILE* fp =fopen("test.txt","rb");char* name =(char*)malloc(20);if(fp ==NULL){printf("Can't open the file.\n");exit(0);}while(fscanf(fp,"%s", name)!=EOF)//因为读取时遇到空格会停止。{printf("%s ", name);}fclose(fp);
fp =NULL;return0;}
以格式化的形式输出 int fprintf ( FILE * stream, const char * format, … ); 其中FILE * stream表示输出流,const char * format表示的是输出格式。 fprintf的返回值是成功输出的格式大小。
#include<stdio.h>#include<stdlib.h>intmain(){
FILE* fp =fopen("test.txt","wb");char* name =(char*)malloc(20);if(fp ==NULL){printf("Can't open the file.\n");exit(0);}gets(name);fprintf(fp,"My name is %s", name);fclose(fp);
fp =NULL;return0;}
重新定义指针位置 int fseek ( FILE * stream, long int offset, int origin ); 其中long int offset表示的是指针相较于参考位置的偏移量,int origin则表示参照位置。 int origin有三种形式: SEEK_SET 表示文件开头位置 SEEK_CUR 表示文件指针的当前位置 SEEK_END 表示文件结束位置
#include<stdio.h>#include<stdlib.h>intmain(){
FILE* fp =fopen("test.txt","wb");char* name =(char*)malloc(20);if(fp ==NULL){printf("Can't open the file.\n");exit(0);}fputs("My name is Lihua.", fp);//先写入一段数据。rewind(fp);//把指针放到开头位置(课加可不加)。fseek(fp,11,SEEK_SET);//把指针位置置于相较于开头偏移处为11的位置。fputs("Wu", fp);//重偏移处为11的位置开始,把那一段数据替换成Wu,最后结果是//My name is Wuhua.(偏移为11的位置是L的位置)fclose(fp);
fp =NULL;return0;}
文件检测 int ferror ( FILE * stream ); 如果相关流没有错会返回0,如果错误则会返回非0。 int feof ( FILE * stream ); 检查是否设置了与流关联的文件尾指示器,如果是,则会返回与零不同的值。
#include<stdio.h>#include<stdlib.h>intmain(){
FILE* fp =fopen("test.txt","rb");char* name =(char*)malloc(20);if(fp ==NULL){printf("Can't open the file.\n");exit(0);}fputc('a', fp);if(ferror(fp))printf("Stream error.\n");//因为是以只读的形式打开,所以不能写入。ferror(fp)这里返回值就为非0while(fgetc(fp)!=EOF);//fgetc每读取一个字符指针往后跳一个字节知道读取失败时返回EOFif(feof(fp))printf("Succeed find the end of file.\n");//因为fgetc返回EOF代表成功读到了结尾,所以feof返回非零值fclose(fp);
fp =NULL;return0;}