文件指针在c中读取,如果EOF则返回null

时间:2016-10-14 09:55:28

标签: c pointers input output

我是一名学生制作一个带文件指针的函数,让我们说stdin并返回一个结构指针。所以我不确定如何开始。遇到EOF时应该返回null指针。

这是我到目前为止所做的:

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;
}

输入文件的示例

chris evans
hello there
as2 ss1
ashley lee
big buildings
d2a 4sa

1 个答案:

答案 0 :(得分:1)

你大概需要这个:

#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);
}

<强>声明:

这是基本的非错​​误检查代码,仍有很大的改进空间,只是为了给你一个想法。