good_evening
good_evening

Reputation: 21739

Read a file line by line for integers

I just want to output 3 integers from the file. Why this doesn't work? I get -1079184140 and similar.

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

   FILE* stream  = fopen(argv[2], "r");

   char line[80];

  for (int i = 0; i < 3; i++)
  {
    fgets(line, 80, stream);
    printf("%d \n", line);
  } 

  fclose(streamForInput);

}

Upvotes: 1

Views: 8587

Answers (5)

user3342227
user3342227

Reputation: 133

To read a file line by line for integers

  void read_file(char *filename, int *readbuff, int size)
   {
       FILE *fp = fopen(filename,"r");
       if(fp == NULL){
          printf("Failed to open file %s \n", filename);
          return;
       }

       /*the condition in for loop checks if the integer was read into
        readbuff[i] and the readbuff is not overflown*/
       for(int i = 0 ; fscanf(fp,"%d\n",&readbuff[i]) == 1  && i < size; ++i);

       fclose(fp);
       return;
   }

Upvotes: 0

effeffe
effeffe

Reputation: 2881

If you know exactly the content of the file (three numbers separated by white space), why not directly read it?

if (fscanf(stream, "%d%d%d", &foo, &bar, &baz) < 3)
    // handle error

printf("%d\n%d\n%d\n", foo, bar, baz);

But if you want to read lines, there are already other good answers.

Upvotes: 1

Michael McGuire
Michael McGuire

Reputation: 1034

I would use sscanf.

int number;
sscanf (line, "%d", &number);
printf ("%d \n", number);

That will pull the first integer on a line. This is not the most secure or robust way, but that is out of scope.

PS:

fclose(streamForInput);

Should be:

fclose(stream);

Upvotes: 4

antak
antak

Reputation: 20739

To print a string, which line is, use %s:

printf("%s \n", line);

Now, if it really were an integer, you could use %d:

int num = atoi(line);
printf("%d \n", num );

What you're seeing is the result of treating a pointer type (which is what a string in C basically is) as an integer type. Since pointers hold memory addresses, that -1079184140 is the actual address the pointer holds, represented as a 32 bit signed integer.

Upvotes: 1

pbhd
pbhd

Reputation: 4467

Hmm. The first problem is:

   printf("%d \n", line);

because line is a char[]. But you use a %d to output it, so you output line, which is an address. So printf prints the address of line... instead you coud use printf ("%d", atoi(line));

Upvotes: 3

Related Questions