user1781966
user1781966

Reputation:

basic file input using C

So im working on learning how to do file I/O, but the book I'm using is terrible at teaching how to receive input from a file. Below is is their example of how to receive input from a file, but it doesn't work. I have copied it word for word, and it should loop through a list of names until it reaches the end of the file( or so they say in the book), but it doesn't. In fact if I leave the while loop in there, it doesn't print anything.

#include <stdio.h>
#include <conio.h>
#define MAX 250
int main()
{

  char name[MAX]; 
  FILE*pRead;

  pRead=fopen("test.txt", "r");
  if (pRead==NULL)
    {
     printf("file cannot be opened");
    }else      


     printf("contents of test.txt");
     while(fgets(name,sizeof(name),pRead)!=NULL){
           {
            printf("%s\n",name);
            fscanf(pRead, "%s", name);
           }


             getch();
   }

Even online, every beginners tutorial I see does some variation of this, but I can't seem to get it to work even a little bit.

Upvotes: 1

Views: 79

Answers (1)

AndersK
AndersK

Reputation: 36092

I believe your array is too small and therefore when you are reading fscanf overwrites memory causing bizarre behavior

If you just want to read the file - presuming now there is one name per line followed by newline in the input file - just read the file using fgets() instead.

#define MAXLINE 256

char name[MAXLINE]; 

while (fgets(name,sizeof(name),pRead)!=NULL)
{
  // do whatever
}

Upvotes: 1

Related Questions