C语言中文件读写参考

C语言中的文件读写分为两种,一种是二进制文件读写,一种是文本文件读写 这里的区分主要是在打开文件时的第二个参数的选择

作者博客 :http://blog.csdn.net/iaccepted


fopen的第二个参数常见的形式有

“rt”      只读打开一个文本文件,只允许读数据 
“wt”      只写打开或建立一个文本文件,只允许写数据
at”      追加打开一个文本文件,并在文件末尾写数据
“rb”      只读打开一个二进制文件,只允许读数据
“wb”       只写打开或建立一个二进制文件,只允许写数据
“ab”       追加打开一个二进制文件,并在文件末尾写数据
“rt+”      读写打开一个文本文件,允许读和写
“wt+”      读写打开或建立一个文本文件,允许读写
“at+”      读写打开一个文本文件,允许读,或在文件末追加数据“
rb+”      读写打开一个二进制文件,允许读和写 
“wb+”      读写打开或建立一个二进制文件,允许读和写
“ab+”      读写打开一个二进制文件,允许读,或在文件末追加数据



1.通过例子来介绍fwrite和fread的用法


#include <stdio.h>
#include <stdlib.h>

#define SIZE 2

typedef struct student{
    char name[10];
    int num;
};

student stu[SIZE+1];

 
void save()
{
	FILE *fp;//http://blog.csdn.net/iaccepted

	int i;

	if((fp=fopen("t.txt","w"))==NULL){
		printf("Error!\n");
		exit(1);
	}
	for(i=0;i<2;++i){
		if(fwrite(&stu[i], sizeof(student), 1, fp) != 1){
			printf("ERROR!\n");
			exit(1);
		}
	}
	fclose(fp);
    
}

void get(){

	FILE * f;
	if((f=fopen("t.txt","r"))==NULL){
		printf("Error!\n");
		exit(1);
	}
	//the following two sentences aim to test the function of fseek
	//fread(&stu[2],sizeof(student),1,f);
	//fseek(f,0,SEEK_END);
	fread(&stu[2],sizeof(student),1,f);
	fclose(f);
}
 
void main()
{
	int i;
	for(i=0;i<SIZE;++i){
		scanf("%s%d",stu[i].name,&stu[i].num);
	}
	save();
	get();

	printf("%s %d\n",stu[2].name,stu[2].num);
}

2.通过例子来介绍fprintf 和 fscanf的用法


#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct student
{
    char name[20];    //姓名
    int num;        //学号
}student;

void main()
{
    FILE *pWrite,*pRead;//http://blog.csdn.net/iaccepted
    struct student tStu,tStu2;
    char *pName = "letuknowit";

	if((pWrite=fopen("t.txt","w"))==NULL){
		printf("Error!\n");
		exit(1);
	}
    

    memcpy(tStu.name,pName,20);
    tStu.num = 1;
    
    fprintf(pWrite,"%d %s\n",tStu.num,tStu.name);
	fprintf(pWrite,"%d %s\n",tStu.num,tStu.name);
    fclose(pWrite);

    if((pRead=fopen("t.txt","r"))==NULL){
		printf("Error!\n");
		exit(1);
	}

    fscanf(pRead,"%d %s\n",&tStu2.num,tStu2.name);
    fclose(pRead);

    printf("%d %s\n",tStu2.num,tStu2.name);
}


用来记录一下常用的程序操作,仅供自己参考


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值