文件的一些操作

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值