Jebathon
Jebathon

Reputation: 4561

C- Reading from a file and getting unexpected results when printing contents of it

I have a program that reads a file from command line (file that consists of integers - see below), puts it into an array and then prints the array.

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

#define SIZEBUFF 1024


int main (int argc, char *argv[])
{

 if (argc < 2)
   {
     printf("Missing file\n");
     return (EXIT_FAILURE);
   }

    FILE *file = fopen (argv[1],"r");
    int integers [144]; //Array that input is stored

    char buffer[SIZEBUFF];
    int count = 0;
    while (fgets(buffer,sizeof (buffer),file) > 0){ // !=EOF gives seg. fault if used
    integers[count] = atoi(buffer);
    count++;

    }

fclose(file);

printf ("The contents of integer array are: \n");

int j;
for (j = 0; j < 144;j++) printf ("%d\t",integers[j]);

return (EXIT_SUCCESS);


}

enter image description here

NOTE: Real file consists of 144 integers. I just took the first 12

How can I print just the numbers that exist in the file?

Upvotes: 0

Views: 50

Answers (3)

ajay
ajay

Reputation: 9680

You should use fscanf to read integers from the file into the array.

int count = 0;
while(fscanf(file, "%d", &integers[count++]) == 1)
    ; // the null statement

int j;
for(j = 0; j < count; j++)
    printf("%d\t", integers[j]);

Upvotes: 0

LearningC
LearningC

Reputation: 3162

This problem is because you wrote code assuming that fgets() reads a single integer from file on each call. But its not so if the integers are stored on same line.

fgets() stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

So here fgets is reading more than one integer at a time from file so atoi() is not getting the integers in file too.
you can use fscanf() to read the integers directly,

fscanf(file,"%d",&integers[count]);

you can loop through this statement 144 times since you know the number of integers in the file or can use,

  fscanf (file, "%d", &integers[count]);    
  while (!feof (file))
    {  
      fscanf (file, "%d", &integers[++count]);      
    }

Upvotes: 2

Scott Hunter
Scott Hunter

Reputation: 49803

You could use fscanf just as you would use scanf to read 144 integers from the console.

Upvotes: 0

Related Questions