gpt4 book ai didi

使用文件和结构的 C 程序

转载 作者:行者123 更新时间:2023-11-30 20:31:31 24 4
gpt4 key购买 nike

我想知道为什么代码不打印输出。二进制文件模式和普通文件模式有什么区别?

#include<stdio.h>
#include <stdlib.h>
typedef struct book_details
{
char book_title[50];
int book_no;
float book_price;
}book_details;

int main()
{
book_details b;
FILE *fp;

fp = fopen("book_list.txt","w+");
if (fp == NULL)
printf("File not found");

fflush(stdin);
printf("Enter Book Title: \n");
gets(b.book_title);
printf("Enter Book ID Number: \n");
scanf("%d",&b.book_no);
printf("Enter Book Price: \n");
scanf("%f",&b.book_price);
fprintf(fp,"Here are the book details");
fwrite(&b,sizeof(b),1,fp);
while (fread(&b,sizeof(b),1,fp) > 0)
printf("%s %d %f\n",b.book_title,b.book_no,b.book_price);
fclose(fp);
}

有哪些错误?

最佳答案

发生这种情况是因为这里使用相同的文件指针 fp 进行读取和写入。您的输出文件是二进制文件,因此只有 fread()fwrite( ) 可以在这里使用。在这种情况下,您不能使用fprintf(fp,"Here are the book details");。这也会导致阅读错误。在这种情况下,有两个解决方案。

  1. Using rewind().

使用函数rewind(),我们可以将文件指针fp倒回到初始状态以读取文件。

试试这个代码:-

#include<stdio.h>
#include <stdlib.h>
typedef struct book_details
{
char book_title[50];
int book_no;
float book_price;

}book_details;

int main()
{
book_details b;
FILE *fp;

fp = fopen("book_list.txt","r+");
if (fp == NULL)
printf("File not found");

printf("Enter Book Title: \n");
gets(b.book_title);
printf("Enter Book ID Number: \n");
scanf("%d",&b.book_no);
printf("Enter Book Price: \n");
scanf("%f",&b.book_price); // removed fprintf();
fwrite(&b,sizeof(b),1,fp);
fflush(stdin);

rewind(fp); // Using rewind();

while (fread(&b,sizeof(b),1,fp) > 0)
printf("%s %d %f\n",b.book_title,b.book_no,b.book_price);
fclose(fp);
}
  1. Using separate read and write FILE pointers.

试试这个代码:-

#include<stdio.h>
#include <stdlib.h>
typedef struct book_details
{
char book_title[50];
int book_no;
float book_price;

}book_details;

int main()
{
book_details b;
FILE *fpwrite,* fpread; // separate File pointers.

fpwrite = fopen("book_list.txt","w");
if (fpwrite == NULL)
printf("File not found");

printf("Enter Book Title: \n");
gets(b.book_title);
printf("Enter Book ID Number: \n");
scanf("%d",&b.book_no);
printf("Enter Book Price: \n");
scanf("%f",&b.book_price); // removed fprintf();
fflush(stdin);
fwrite(&b,sizeof(b),1,fpwrite);
fclose(fpwrite);

fpread = fopen("book_list.txt","r");
while (fread(&b,sizeof(b),1,fpread) > 0)
printf("%s %d %f\n",b.book_title,b.book_no,b.book_price);
fclose(fpread);
}

单独的文件指针被认为更好,因为它提高了源代码的可读性。

关于使用文件和结构的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50636545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com