嘿!我目前正在为即将到来的大学作业做一些准备,但遇到了一些困难。
我必须编写一个 C 数据库应用程序,将书籍详细信息存储到一个文件中,并允许我调用和删除它们。我在读取文件时遇到一些问题,当我列出所有条目时,条目不会显示(选项 3)。
我查看了数据库文件,所以我认为它已被正确写入。
这是我的代码的基本功能:
#include<stdio.h>
#include <stdlib.h>
// Global Varables
FILE *fp, *ft;
// Structs
typedef struct Books
{
int id;
char title[25];
char forename[25];
char surname[25];
char isbn[13];
}Books;
void displayMenu()
{
printf("Options");
}
void runapp()
{
int option;
char isbn[20];
char deleteOrNot[2];
Books book;
fp = fopen("database.dat", "a+");
if (fp == NULL)
{
printf("Failed to open file.");
}
long int booksize = sizeof(book);
do
{
displayMenu();
printf("Enter menu option: ");
scanf("%i", &option);
switch(option)
{
// =================================================================
// -------- OPTION 1: Add a new book
// =================================================================
case 1:
fseek(fp, 0, SEEK_END);
printf("Please enter the books title: ");
scanf("%s", book.title);
printf("Please enter the authors first name: ");
scanf("%s", book.forename);
printf("Please enter the authors surname: ");
scanf("%s", book.surname);
printf("Please enter the ISBN number: ");
scanf("%s", book.isbn);
fwrite(&book, booksize, 1, fp);
fflush(stdin);
break;
// =================================================================
// -------- OPTION 2: Search and delete
// =================================================================
case 2:
// Search and delete
break;
// =================================================================
// -------- OPTION 3: List all books
// =================================================================
case 3:
rewind(fp);
while(fread(&book, booksize,1, fp))
printf("%s", book.title);
printf("\n\nPress any key to return to menu.");
getch();
break;
// =================================================================
// -------- OPTION 4: Exit the application
// =================================================================
case 4:
fclose(fp);
exit(0);
break;
}
if (system("cls")) system("clear");
}while(option != "\n");
}
int main()
{
runapp();
return 0;
}
任何解决这个问题的帮助都会很棒!
也请随时给我一些关于我的代码的提示。
最佳答案
在 main
中,您正在执行以下不正确的操作:
int option;
....
}while(option != "\n");
关于C - 文件 I/O,不是从文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5282548/