fopen(const char *path, const char *mode);
fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
几个文件操作函数的简单使用
#include<stdio.h>
#include<stdlib.h>
#define N 5
typedef struct
{
int year;
int mon;
int day;
}time;
typedef struct
{
int num;
char title[32];
char author[8];
char press[32];
float price;
time t;
}book;
------------------
void save(book *b)
{
int i;
FILE *fp;
if((fp=fopen("books.dat","wb"))==NULL)
{
printf("open books.dat failed!!/n");
exit(0);
}
for(i=0; i<N; i++)
{
if(fwrite(&b[i],sizeof(book),1,fp)!=1)
printf("save books[%d] info error!!/n");
}
fclose(fp);
}
------------------------
void change(int n, float price )
{
FILE *fp;
book b;
if((fp=fopen("books.dat","rb+"))==NULL)
{
printf("open books.dat failed!!/n");
exit(0);
}
fseek(fp,n*sizeof(book),0);
fread(&b,sizeof(book),1,fp);
b.price = price;
fseek(fp,n*sizeof(book),0);
fwrite(&b,sizeof(book),1,fp);
fclose(fp);
}
----------------------
void display()
{
FILE *fp;
int i;
book b;
if((fp=fopen("books.dat","r"))==NULL)
{
printf("open books.dat failed!!/n");
exit(0);
}
for(i=0 ; i<N; i++)
{
fread(&b,sizeof(book),1,fp);
printf("%d/t%s/t%s/t%s/t%f/t%d/t%d/t%d/n",b.num,b.title,/
b.author,b.press,b.price,b.t.year,b.t.mon,b.t.day);
}
fclose(fp);
}
------------------------
int main()
{
book books[N];
int i;
int n;
float price;
for(i=0; i<N; i++)
{
printf("input the %ds book info:/n",i);
printf("num/ttiltle/tauthor/tpress/tprice/tyear/tmon/tday/n");
scanf("%d %s %s %s %f %d %d %d",&books[i].num,/
&books[i].title,&books[i].author,&books[i].press,/
&books[i].price,&books[i].t.year,/
&books[i].t.mon,&books[i].t.day);
}
save(books);
printf("the books info is:/n");
display();
printf("input which book you want to change:");
scanf("%d",&n);
printf("input a new pricef:");
scanf("%f",&price);
change(n-1,price);
printf("after change the books info:/n");
display();
return 0;
}
2010-07-22