文件的读写,已经弄了很久。这中间自己也玩了很久,学的较少。主要是自己没有耐下心来看,也没有完全弄清楚fprintf/fscanf fread/fwrite 这几个函数的区别。在做的时候也是眉毛胡子一把抓。没有分文本文件的读写和二进制文件的读写。两者混在一起,结果写进去的数据总是乱码。
一、文本文件的读写
首先我们应该从一个简单的文件读写开始:
1、写入一行字符串。
#include<stdio.h>
main()
{
FILE *fp;
int i=333;
char *s="this is a sting!";
fp=fopen("aa.txt","w");
fprintf(fp,"%d\n",i);
fprintf(fp,"%s",s);
fclose(fp);
return 0;
}
——————结果——————
显示:
this is a sting!
【也可以加fputs("***",fp);】
2、写入学生信息:
#include<stdio.h>
#define SIZE 2
typedef struct
{
char name[5];
int num;
int age;
char addr[15];
}student;
student stu[SIZE];
main()
{ int i;
FILE *fp;
char file[]="/root/a4.txt";
fp=fopen(file,"a");
if(fp==NULL)
{
printf("cant't open file %s.\n",file);
return 0;
}
else
{
printf("%s is opened.\n",file);
}
printf("please enter data of students:\n");
for(i=0;i<SIZE;i++)
{
scanf("%s%d%d%s",&stu[i].name,&stu[i].num,&stu[i].age,&stu[i].addr);
fprintf(fp,"%s %d %d %s\n",stu[i].name,stu[i].num,stu[i].age,stu[i].addr);
}
fclose(fp);
}
——————结果——————
键盘输入:liu 20121220 22 hubei
wang 2012202 21 jingzhou
a4.txt中显示:
liu 20121220 22 hubei
wang 2012202 21 jingzhou
二、二进制文件的读写
1、一个简单的写入:
#include<stdio.h>
imain()
{
FILE *fp;
char s[]="hello linux";
fp=fopen("a5.bin","a");
fwrite(s,sizeof(s),1,fp);
fclose(fp);
return 0;
}
——————结果——————
显示:
hello linux
2、写入学生信息:
#include<stdio.h>
#define SIZE 2
struct student_type
{
char name[5];
int num;
int age;
char addr[15];
}stud[SIZE];
main()
{ int i;
FILE *fp;
char file[]="a2.dat";
fp=fopen(file,"w");
if(fp==NULL)
{
printf("cant't open file %s.\n",file);
}
else
{
printf("%s is opened.\n",file);
}
printf("please enter data of students:\n");
for(i=0;i<SIZE;i++)
{
scanf("%s%d%d%s",&stud[i].name,&stud[i].num,&stud[i].age,&stud[i].addr);
fwrite(&stud[i],sizeof(struct student_type),1,fp);
}
for(i=0;i<SIZE;i++)
{
fread(&stud[i],sizeof(struct student_type),1,fp);
printf("%-5s %4d %4d %-15s\n",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
}
fclose(fp);
return 0;
}
——————结果——————
显示:
hh 444 4 usa
bb 555 4 usw
hh 444 4 usa
bb 555 4 usw