0

I am a student making a function that takes an file pointer, lets say stdin and returns a struct pointer. So I'm not sure how to begin. It should return a null pointer when EOF is encountered.

This is what I made so far:

typedef struct book
{
    char *author;
    char *title;
    char *bookcode;
} Book;

Book *getBook(FILE *pointer)
{
    Book *p;
    int c;
    while ((c = fgetc(pointer)) != EOF)
    {
     //create book
      putchar (c);
    }
    }
    return p;
}

example of input file

chris evans
hello there
as2 ss1
ashley lee
big buildings
d2a 4sa
Jon
  • 37
  • 4
  • Please elaborate your question and tell us what you are actually trying to achieve. We need a larger picture of your problem. Also read [this](http://xyproblem.info/) and [this](http://stackoverflow.com/help/how-to-ask). And learn how to format code. What is `Book`? What does your file contain ? – Jabberwocky Oct 14 '16 at 09:58
  • Re your edit, please see [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Weather Vane Oct 14 '16 at 10:07
  • 1
    What is the format of the file ?? Give us an example of that file containing say 2 books. – Jabberwocky Oct 14 '16 at 10:08
  • Are you familiar with pointer and the concept of dynamic memory allocation ? If no, get familiar with that first. – Jabberwocky Oct 14 '16 at 10:12
  • Use `fgets` to read in text. Remember each string input will have a `newline` at its end which you will have to remove. – Weather Vane Oct 14 '16 at 10:34

1 Answers1

1

You roughly need this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct book
{
  char *author;
  char *title;
  char *bookcode;
} Book;

void freeBook(Book *p)
{
  free(p->author);
  free(p->title);
  free(p->bookcode);
  free(p);
}

Book *getBook(FILE *pointer)
{
  Book *p = malloc(sizeof(Book));
  p->author = NULL;
  p->title = NULL;
  p->bookcode = NULL;

  char line[200];

  if (fgets(line, sizeof(line), pointer) != NULL)
    p->author = strdup(line);

  if (fgets(line, sizeof(line), pointer) != NULL)
    p->title = strdup(line);

  if (fgets(line, sizeof(line), pointer) != NULL)
    p->bookcode = strdup(line);

  if (feof(pointer))
  {
    freeBook(p);
    return NULL;
  }
  else
    return p;
}

int main()
{
  Book *pBook;

  do
  {
    pBook = getBook(stdin);

    // do something with pBook


   freeBook(pBook);   // free memory of book if you are done with it
                      // and only if you are done with it.  
  } while (pBook != NULL);
}

Disclaimer:

This is basic, non error checking code and there is still much room for improvement, it's just to give you an idea.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Thanks a lot but how do you skip the first book once the function is called so the second book will be returned like in the example input file – Jon Oct 14 '16 at 16:07