文件概述
文件分类
文件的打开与关闭
wt rt at 文本文件
文件的读写
文件结束为1 文件未结束为0
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *pic,*file,*new_file;
char a[20],b[20],c[20];
char ch;
printf("请输入照片的名称: ");
scanf("%s",a);
printf("请输入文件的名称: ");
scanf("%s",b);
printf("请输入要合成文件的名称: ");
scanf("%s",c);
if( !(pic = fopen(a,"rb")) )
{
printf("无法打开照片\n");
}
if( !(file = fopen(b,"rb")) )
{
printf("无法打开文件\n");
}
if( !(new_file = fopen(c,"wb")) )
{
printf("无法打开新文件");
}
while(!(feof(pic)) )
{
ch = fgetc(pic);
fputc(ch,new_file);
}
fclose(pic);
while(!(feof(file)) )
{
ch = fgetc(file);
fputc(ch,new_file);
}
fclose(file);
fclose(new_file);
system("pause");
}
字符串输入输出
数据块的读写函数
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
struct student
{
char name[10];
int num;
int age;
char addr[15];
}stu[SIZE];
void save()
{
FILE *fp;
int i;
if( !(fp = fopen("student-list","wb")))
{
printf("Cannot open the file!\n");
return;
}
for(i=0;i<SIZE;i++)
{
if( fwrite(&stu[i],sizeof(struct student),1,fp) != 1)
{
printf("File write error!\n");
fclose(fp);
}
}
}
void main()
{
int i;
printf("Please input the student's name,num,age and address: \n");
for(i=0;i<SIZE;i++)
{
scanf("%s %d %d %s",stu[i].name,&stu[i].num,&stu[i].age,&stu[i].addr);
}
save();
}
void load()
{
FILE *fp;
int i;
if( !(fp = fopen("student-list","r")))
{
printf("Cannot open the file\n");
return;
}
for(i=0;i<SIZE;i++)
{
fread(&stu[i],sizeof(struct student),1,fp);
}
fclose(fp);
}
格式化读写函数
顺序读写和随机读写
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
struct student
{
char name[10];
int num;
int age;
char addr[15];
}boy;
void main()
{
FILE *fp;
int i=1;
if( !(fp = fopen("student-list","r")))
{
printf("Cannot open the file!\n");
return;
}
rewind(fp);
fseek(fp,i*sizeof(struct student),0);
fread(&boy,sizeof(struct student),1,fp);
printf("name\tnumber age addr\n");
printf("%s\t%5d %7d %s\n",boy.name,boy.num,boy.age,boy.addr);
system("pause");
}
出错的检测