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);
}
用来记录一下常用的程序操作,仅供自己参考