首页

2009年5月14日星期四

C文件读取与保存!

1. C文件读取与保存!
2. #include
3. #include
4. #define MAXT 40
5. #define MAXA 40
6. #define MAXB1 10 //图书的最多本书
7. struct book{
8. char title[MAXT];
9. char author[MAXA];
10. float value;
11. };
12. int main(void)
13. {
14. struct book library[MAXB1];
15. int count=0;
16. int index,filecount;
17. FILE *pbooks;
18. int size = sizeof(struct book);
19. if((pbooks=fopen("book.dat","a+b"))==NULL)
20. {
21. fputs("Can't open book.dat file\n",stderr);
22. exit(1);
23. }
24. rewind(pbooks);
25. while(count
26. {
27. if(count==0)
28. puts("Current contents of book.dat:");
29. printf("%s by %s:$%.2f\n",library[count].title,library[count].author,library[count].value);
30. count++;
31. }
32. filecount=count;
33. if(count==MAXB1)
34. {
35. fputs("The book.dat file is full.",stderr);
36. exit(2);
37. }
38. puts("Please add new book titles.");
39. puts("press [enter] at the start of a line to stop.");
40. while(count
41. {
42. puts("Now enter the author.");
43. gets(library[count].author);
44. puts("Now enter the value.");
45. scanf("%f",&library[count++].value);
46. while(getchar()!='\n')
47. continue;
48. if(count
49. puts("Enter the next title.");
50. }
51. if(count>0)
52. {
53. puts("Here is the list of your books:");
54. for(index=0;index
55. printf("%s by %s:$%.2f\n",library[index].title,library[index].author,library[index].value);
56. fwrite(&library[filecount],size,count-filecount,pbooks);
57. }
58. else
59. puts("No books?Too bad.\n");
60. puts("Bye.\n");
61. fclose(pbooks);
62. return 0;
63. }


没有评论:

发表评论