- 论坛徽章:
- 0
|
本帖最后由 冷寒生 于 2013-05-08 20:40 编辑
下面这个程序的作用是向文件添加书籍,利用fread()和fwrite();
fread()函数可以正常向文件读取,然后输入到控制台显示出来,(说明文件里面的内容是正确的)
可是fwrite()写入到文件后,直接打开文件,就会出现烫。。(说明这个二进制不应该用文本文件打开,那应该用什么软件打开查看了? 还有如果直接保存为dat格式的,可以直接查看吗?)
![]() - // booksave.c
- # include <stdio.h>
-
- # include <stdlib.h>
-
- # define MAXTITL 40
- # define MAXAUTL 40
- # define MAXBKS 10
-
- struct book
- {
- char title[MAXTITL];
- char author[MAXAUTL];
- float value;
- }; //注意结构类型后面要加分号
-
- int main (void)
- {
- struct book library[MAXBKS];
- FILE * pbooks;
- int count = 0;
- int size = sizeof (struct book);
- int index;
- int filecount;
- if ((pbooks = fopen ("book.txt", "a+b")) == NULL)
- {
- printf ("bad.\n");
- exit (1);
- }
- while (count < MAXBKS && fread (&library[count], size, 1, pbooks) ==1)
- {
- if (count == 0)
- printf ("Current contents of book.txt: \n");
- printf ("%s by %s: %.2f\n", library[count].title,
- library[count].author, library[count].value);
- count++;
- }
- filecount = count;
-
- if (count == MAXBKS)
- {
- puts ("the bkskk");
- exit (2);
- }
-
- puts ("please add new book titles.");
- puts ("press [enter] at the start of a line to stop.");
- while (count < MAXBKS && gets (library[count].title)
- && library[count].title[0] != '\0')
- {
- puts ("enter the author");
- gets (library[count].author);
- puts ("now enter the value.");
- scanf ("%f", &library[count++].value);
- while (getchar () != '\n')
- continue;
- if (count < MAXBKS)
- puts ("enter the next title.");
-
- }
- if (count > 0)
- {
- puts ("here is the list of your books.");
- for (index = 0; index < count; index++)
- {
- printf ("%s by %s : %.2f.\n", library[index].title,
- library[index].author, library[index].value);
-
- }
- fwrite (&library[filecount], size, count - filecount, pbooks);
- }
- else
- {
- puts ("no book, ");
-
- }
- puts ("goodbye.");
- fclose (pbooks); //注意一定要关闭文件;
-
- return 0;
- }
复制代码 |
|