1

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.

3
  • Are you sure you were able to open the file in the first place? Commented Nov 17, 2012 at 16:49
  • how does the input file look like, is it one entry per line or all entries without newline inbetween? Commented Nov 17, 2012 at 16:49
  • if I take the while loop out it prints out the first name on the file, but nothing after that, So I do believe it is opening the file. @andersK I played around with the file, I've had it set up where each name was on a new line, each name on a new line with a space, and each name on the same line separated by a space. Commented Nov 17, 2012 at 16:54

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

5 Comments

tried your suggestion, and I get the same results. This is driving me nuts! I got something much bigger then this I am working on, but I can't get that to work until I can figure out why this isn't working!
so you only get first line in file? that is odd. maybe you do not have any more newlines in it besides the one on the first line although should give some kind of output then.
yes, after making the edits you suggested, and taking out the first fscanf which was originally above the while loop, it now prints, but just the first line.
edits have been made in the original post to reflect what I have.
ok just remove the second fscanf and it should work. the fgets will keep on reading each row from the file until the end, there is no need for an extra fscanf.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.