<分区>
好吧,在我的代码中,我正在将一个结构数组写入一个文件。当我检查文件时,信息就在那里,但是当我调用 fread() 时,当我尝试访问数据时什么也没有打印出来。我在想 fwrite() 指向的数据在结束时不在正确的位置。提前致谢。
这里是main()
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct NOVEL
{
char title[50];
char newtitle[50];
char author[50];
char newauthor[50];
char genre[20];
char newgenre[20];
char quality[20];
int numpages;
};
int addbooks(struct NOVEL[], char[]);
void displaybooks(struct NOVEL[], int, char[]);
void sortbooks(struct NOVEL[], int);
void title(struct NOVEL[], int);
void author(struct NOVEL[], int);
void category(struct NOVEL[], int);
void numpages(struct NOVEL[], int);
int main()
{
//Define the variables
int num, numbooks = 0;
char repeat = 'Y', name[50];
struct NOVEL library[100] = {0};
//Asks what the user wants to do
while (repeat == 'Y' || repeat == 'y')
{
printf("1. Add Books\n2. Display Books\n3. Sort Books\nPlease enter your choice: ");
scanf("%i", &num);
getchar();
switch (num)
{
//Add Books
case 1:
numbooks = addbooks(library, name);
break;
//Display Books
case 2:
displaybooks(library, numbooks, name);
break;
//Sort Books
case 3:
sortbooks(library, numbooks);
break;
default:
printf("Incorrect Number Entered!\n");
}
printf("\nWould you like to do something else? [Y/N]: ");
scanf(" %c", &repeat);
}
return 0;
}
这是我创建的 addbooks() 函数:
int addbooks(struct NOVEL books[], char filename[])
{
static int i = 0;
char stop = 'Y';
FILE *fpnew = NULL;
//The user adds their books here
while (i <= 29 && (stop == 'Y' || stop == 'y'))
{
printf("Please enter the name of the file you would like to create/use: ");
gets(filename);
if ((fpnew = fopen(filename, "wb")) == NULL)
{
printf("Can't open the file name: %s", filename);
exit(1);
}
printf("Please enter your book's title: ");
gets(books[i].title);
printf("Please enter your book's author: ");
gets(books[i].author);
printf("Please enter your book's genre: ");
gets(books[i].genre);
printf("Please enter your book's rating [1-10]: ");
gets(books[i].quality);
printf("Please enter your book's number of pages: ");
scanf("%i", &books[i].numpages);
getchar();
i++;
printf("Add another book? [Y/N]: ");
scanf("%c", &stop);
getchar();
}
fwrite(books, sizeof(struct NOVEL), i, fpnew);
fclose(fpnew);
return i;
}
这是我制作的 displaybooks() 函数:
void displaybooks(struct NOVEL books1[], int numberofbooks, char dfilename[])
{
int j;
FILE *fpdisplay = NULL;
//struct NOVEL read[30];
printf("Please enter the name of the file you would like to create/use: ");
gets(dfilename);
if ((fpdisplay = fopen(dfilename, "rb")) == NULL)
{
printf("Can't open the file name: %s", dfilename);
exit(1);
}
fread(books1, sizeof(struct NOVEL), numberofbooks, fpdisplay);
fclose(fpdisplay);
//Prints out the book's information
printf("%-30s%-30s%-30s%-30s%-30s\n", "Title", "Author", "Genre", "Quality", "Number of Pages");
for (j = 0; j < numberofbooks; j++)
{
printf("%-30s%-30s%-30s%-30s%-30i\n", books1[j].title, books1[j].author, books1[j].genre, books1[j].quality, books1[j].numpages);
}
}