我正在从文件读取数据到我的列表。每个数据都逐行写入我的txt。我使用fgets读取包含字符的行,不幸的是,它也读取'\ n'。我需要阅读一些内容,直到在代码中看到“ \ n”为止。我使用fscanf(“ [^ \ n] c”)这样的东西,它不起作用。我该怎么办?(对不起我的英语不好。我希望自己能解释一下)
//Example data
/*
Computer
computer science bla bla
bla bla bla is author
123
66
15.5
1
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct library
{
char catagory[50];
char available[18];
char book_name[50];
char author[50];
int book_id;
int quantity;
double price;
int shelf_no;
struct library* next;
}node;
node* read_from_file(node* head);
void view_book(node* root);
int main() {
node* root;
root = NULL;
root = read_from_file(root);
view_book(root);
return 0;
}
node* read_from_file(node* head) {
node* iter;
FILE* fptr = fopen("data.txt", "r");
fseek(fptr, 0, SEEK_END);
if (ftell(fptr) == 0)
{
printf("*");
fclose(fptr);
return NULL;
}
else {
fseek(fptr, 0, SEEK_SET);
head = (node*)calloc(1,sizeof(node));
head->next = NULL;
iter = head;
head->book_id = -1;
while (feof(fptr) != 1) {
iter->next = (node*)calloc(1, sizeof(node));
iter = iter->next;
iter->next = NULL;
fgets(iter->catagory,50,fptr);
fgets(iter->book_name, 50, fptr);
fgets(iter->author, 50, fptr);
fscanf(fptr, "%d", &iter->book_id);
fscanf(fptr, "%d", &iter->quantity);
fscanf(fptr, "%lf",&iter->price);
fscanf(fptr, "%d", &iter->shelf_no);
}
return head;
fclose(fptr);
}
}
void view_book(node* root) {
printf("############################# BOOK LIST #############################\n");
printf("Category\tID\tBook Name\tAuthor\tQTY\tPRICE\tShelf No\n");
node* move;
move = root;
while (move != NULL) {
printf("%s %d %s %s %d %0.2lf %d\n", move->catagory, move->book_id, move->book_name, move->author, move->quantity, move->price, move->shelf_no);
move = move->next;
}
}
fscanf(fptr, "%[^\n]%*c", &iter->catagory);
这是解决方案