以C读取特定格式的文本文件

问题描述 投票:0回答:1

我一直试图读取一个文本文件,其中包含具有特定格式的C语言书籍数据库。这是我到目前为止的内容:

#include "database_main.h"

struct Book getDetailsFromFile(FILE *ptr)
{
    struct Book bookVar;    /*new book variable as struct*/
    char title[MAX_TITLE_LENGTH+1], author[MAX_AUTHOR_LENGTH+1];   /*temp variables to input data*/
    int year;

    fscanf(ptr, "Title: %100[0-9a-zA-Z ]\n", title);    /*fscanf collecting up to 100 character of only numbers or letters*/
    fprintf(stderr, "%s\n", title);

    fscanf(ptr, "Author: %100[0-9a-zA-Z ]\n", author);
    fprintf(stderr, "%s\n", author);

    fscanf(ptr, "Year: %i\n\n", &year);
    fprintf(stderr, "%i\n", year);

    strcpy(bookVar.title, title);   /*transfering values to stuct*/
    strcpy(bookVar.author, author);
    bookVar.year = year;
    bookVar.right = NULL;
    bookVar.left = NULL;
    return bookVar;
}

/* read file containing database of books */
void read_book_database ( char *file_name )
{
    FILE *fptr;   /*file pointer*/
    if ((fptr = fopen(file_name, "r")) == NULL) {
        fprintf(stderr, "Error! opening file\n");   /*catch error*/
    }
    else
    {
        while (feof(fptr) == 0) /*do until end of file*/
        {
            addBook(getDetailsFromFile(fptr));   /*adds book to database from the file*/
            fprintf(stderr, "Got Book\n");
        } 
        fprintf(stderr, "closing file\n");
        fclose(fptr);
    }
}

运行代码时,它会连续重复“ Got Book”,而不会打印出书的任何细节。

我也尝试过使用fgets()来输入数据,但是似乎将年份字段分离到了数据库中一本全新的书中,没有其他信息。这不是addBook()的问题,因为它已经通过手动输入进行了测试并且可以正常工作。

第二fgets()不会剪切标题:以及文件每一行开头的此类字段。我尝试了其他一些在线解决方案,但是都没有用。

感谢您能提供的任何帮助。

还请注意,这是使用ANSI标准编译的。

c parsing text-files
1个回答
0
投票

所以while(feof(fptr)== 0)成了问题,我现在将整个内容更新为以下内容:

void read_book_database ( char *file_name )
{
    char c[1000];
    FILE *fptr;
    if ((fptr = fopen(file_name, "r")) == NULL) {
        fprintf(stderr, "Error! opening file\n");
    }
    else
    {
        struct Book newBook;
        for(newBook;fscanf(fptr, "Title: %100[0-9a-zA-Z ,]\nAuthor: %100[0-9a-zA-Z ,]\nYear: %i\n\n", &(newBook.title), &(newBook.author), &(newBook.year))==3;)
        {
            fprintf(stderr, "Title: %s\nAuthor: %s\nYear: %i\n\n", newBook.title, newBook.author, newBook.year);
            addBook(newBook);
            /*addBook(getDetailsFromFile(fptr));*/
            fprintf(stderr, "Got Book\n");
        } 
        fprintf(stderr, "closing file\n");
        fclose(fptr);
    }
}

它现在确实在程序的不同点引起了一些问题,但是我认为这与文本文件的读取无关,因此我相信这个特定问题已得到解决。谢谢大家的帮助

© www.soinside.com 2019 - 2024. All rights reserved.