|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 17876597634 于 2021-10-25 17:37 编辑
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Date
{
int year;
int month;
int day;
};
struct Book
{
char name[40];
char author[40];
char publisher[40];
struct Date date;
};
int main(void)
{
FILE *fp;
struct Book *book_for_write, *book_for_read;
book_for_read = (struct Book *)malloc(sizeof(struct Book));
book_for_write = (struct Book *)malloc(sizeof(struct Book));
if (book_for_read == NULL || book_for_write == NULL)
{
printf("分配内存失败!\n");
exit(1);
}
if ((fp = fopen("book.txt", "w")) == NULL)
{
printf("打开文件失败!\n");
exit(EXIT_FAILURE);
}
strcpy(book_for_write->name, "<<带你学c带你飞>>");
strcpy(book_for_write->author, "小甲鱼");
strcpy(book_for_write->publisher, "清华出版社");
book_for_write->date.year = 2017;
book_for_write->date.month = 11;
book_for_write->date.day = 11;
fprintf(fp, "%s,%s,%s,%d-%d-%d", book_for_write->name, book_for_write->author, book_for_write->publisher, book_for_write->date.year, book_for_write->date.month, book_for_write->date.day);
fclose(fp);
if ((fp = fopen("book.txt", "r")) == NULL)
{
printf("打开文件失败!\n");
exit(EXIT_FAILURE);
}
while(!feof(fp))
{
fscanf(fp, "%s,%s,%s,%d-%d-%d", book_for_read->name, book_for_read->author, book_for_read->publisher, &book_for_read->date.year, &book_for_read->date.month, &book_for_read->date.day);
printf("书名: %s, ", book_for_read->name);
printf("作者: %s, ", book_for_read->author);
printf("出版社: %s, ", book_for_read->publisher);
printf("日期: %d-%d-%d\n", book_for_read->date.year, book_for_read->date.month, book_for_read->date.day);
}
fclose(fp);
free(book_for_write);
free(book_for_read);
return 0;
} |
-
|