My question is if would be possible to ignore a specific part of a txt file later stored in a struct using fscanf()
.
For the purpose of the example let me say I have a txt file made out of this text:
Title: C Programming Language
Author: Dennis Ritchie
Publication year: 1978
...
And I want to store the data in a struct like this one ignoring the words Title:
, Author:
, Publication year:
and so on:
struct book {
char title[MAX];
char author[MAX];
int pubblication_year;
...
};
This is the code I have implemented in order to store the data:
fscanf(fp, "%[^\n]%*c\n", newOne->books.title); //titolo
fscanf(fp, "%[^\n]%*c\n", newOne->books.author); //autore
fscanf(fp, "%d\n", &newOne->books.pubblication_year); //anno pubblicazione
...
HERE A MINIMAL EXAMPLE:
#include <stdio.h>
#include <stdlib.h>
#define MAX 30
struct book {
char title[MAX];
char author[MAX];
};
struct booklist {
struct book books;
struct booklist *next;
};
int main() {
struct booklist *head = NULL, *newOne, *temp; //temp made in order to clear the heap once the program is termined
FILE *fp;
fp = fopen("FileName.txt", "r");
if(fp == NULL) {
printf("Something wrong happened, the program will close!\n");
system("pause");
exit(1);
} else {
newOne = (struct booklist *)malloc(sizeof(struct booklist));
if(newOne == NULL) {
printf("Error, not enough space to store the new book, the program will close!\n");
system("Pause");
exit(1);
}
fscanf(fp, "%[^\n]%*c\n", newOne->books.title); //ADDING THE TITLE TO THE NODE
fscanf(fp, "%[^\n]%*c\n", newOne->books.author); //SAME FOR THE AUTHOR
//adding the new one node created to the head of the list
newOne->next = head;
head = newOne;
}
while (newOne != NULL) { //cleaning the heap once the program is termined
temp = newOne;
newOne = newOne -> next;
free(temp);
}
fclose(fp);
return 0;
}
It is possible or not to do so?