【c】文件的读写

文件输入输出

类型:文本文件和二进制文件
打开方式
r:只读; r+:可读可写
w:只写; w+:可读可写 (写的时候会覆盖原来的(若文件先前已经存在))
a:追加方式写入 a+:追加方式可读可写
rb、wb、ab+等:二进制方式的读写

文件的打开和关闭

FILE* fopen(const charfilename,const char mode);//打开文件,参数:文件名,打开方式

int fclose(FILE* stream);//关闭文件,参数:文件指针

数据块的读写

size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

ptr:要读写的数据;size:每块数据的字节大小;nmemb:多少块数据;stream:文件指针

格式化的读写

int fscanf(FILE *stream, const char *format, …);//读取不了空格
注意:可变参数全部都是指针类型
int fprintf(FILE *stream, const char *format, …);//写入文件,参数:文件指针,格式,可变参数
注意:格式之间要用空格隔开,不然会粘连到一起

单个字符或字符串的读写

读(从文件get)
int fgetc(FILE *stream);//读入一个字符
char *fgets(char *s, int size, FILE *stream);//读入size个字符,存到字符串s
int getc(FILE *stream);//等效fgetc

写(put到文件)
int fputc(int c, FILE *stream);//写入字符
int fputs(const char *s, FILE *stream);//写入字符串,不包含’\0’(文件结束符)
int putc(int c, FILE *stream);//写入字符,等效fputc

获取或改变指针位置(读多遍文件或多次同个数据)

void rewind(FILE* stream);//将文件指针重新定位到开头

int fseek(FILE* stream,long offset,int where);//将文件指针移动到任意位置
参数:文件指针、偏移值、位置
位置:

文件开头常量名常量值
文件头SEEK_SET0
当前位置SEEK_CUR1
文件尾SEEK_END2
#include<stdio.h>
typedef struct
{       
        char name[12];
        int id:16;
        int class:16;
}student;
int main()
{
        FILE* file=fopen("test.txt","w+");//读写覆盖方式打开文件
        if(file)//判断文件是否打开
        {
                printf("open successfully!\n");
        }
        else
                perror("open failed!\n");
		//创建一个结构体数组,存入文件,用fread和fwrite读写
        student st1[2]={{"Amy",1234,3},{"Mike",1111,3}};
        student st2[2];
        fwrite(st1,sizeof(student),2,file);
        rewind(file);//将文件指针重新定位到文件头
        fread(st2,sizeof(student),2,file);

        printf("file:\n");
        int i=2;
        while(i--)
                printf("name:%s\tid:%d\tclass:%d\n",st2[1-i].name,
                        st2[1-i].id,st2[1-i].class);
        fclose(file);

        FILE* file1=fopen("test1.txt","w+");
        if(!file1)
                perror("open failed!");
        else
                printf("open successfully!");
        //用fscanf和fprintf进行读写
		int id2,id1=1234;
        int n2,n1=1111;
        char str2[10],str1[10]="iiiii";
        fprintf(file1,"%s %d %d",str1,id1,n1);//格式之间要用空格,不然会粘连
        //rewind(file1);
        fseek(file1,0,SEEK_END);//将文件指针重新定位到文件头
		fscanf(file1,"%s%d%d",str2,&id2,&n2);//可变参数,要使用指针类型
        printf("str2=%s\tid2=%d\tn2=%d\n",str2,id2,n2);
        fclose(file1);
        return 0;
}

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值