0

I have a text file that looks like this:

1 2 4
3 5 2
9 7 6
4 2 6

of an unknown size upto 50 lines.

I am trying to store the ints in an array of struct

typedef struct column{
int col_1;
int col_2;
int col_3;
} column;

I have created the array of stuct column

column column[50];

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


FILE * myfile;
 int i = 0;

if ((myfile = fopen("/home/numbers.txt","r"))==NULL)
{
    printf("File %s not found\n", "/home/numbers.txt");
    exit(0);
}
if ("/home/numbers.txt" == NULL)
{
    printf("There was an error reading %s", "/home/numbers.txt");

}

while(fscanf(myfile,"%d %d %d", &column[i++].col_1, &column[i].col_2, &column[i].col_3) == 3)
{
   printf("\n%d %d %d", column[i].col_1, &column[i].col_2, &column[i].col_3);
}  

I get a list of numbers like this

    -420921 -420924 -420927

It appears to be some memory addresses, because they are obviously not the actual numbers.

My problem is the get the ints rather than some rather random numbers, i have tried & before the variables in the printf, and that didnt work, and the other way around.

Your help would be greatly appreciated.

user476145
  • 435
  • 2
  • 9
  • 13

3 Answers3

2
if ("/home/numbers.txt" == NULL)

...will never be true.

Try changing your loop a bit:

while(i < 50 && fscanf(myfile,"%d %d %d", &column[i].col_1, &column[i].col_2, &column[i].col_3) == 3)
{
   printf("\n%d %d %d", column[i].col_1, column[i].col_2, column[i].col_3);
   i++;
} 

...as it is, you're incrementing your counter while the arguments to scanf are being determined, passing in who-knows-what.

sje397
  • 41,293
  • 8
  • 87
  • 103
  • "you're incrementing your counter after the first value is read, and not reading into the right index for the rest." Not really. Nothing will be read until the function is called, and that's after the arguments are evaluated. So it's not after the first value is read. But the order of evaluation is not specified, so you are correct that the other two integers may nor may not be read using the incorrect index – The Archetypal Paul Dec 16 '10 at 11:19
  • Thanks! Its always the simple things! – user476145 Dec 16 '10 at 11:33
0

Numerous things wrong here - this:

if ("/home/numbers.txt" == NULL)
{
    printf("There was an error reading %s", "/home/numbers.txt");

}

does not do anything sensible - get rid of it. and your loop code has undefined behaviour. Increment your index in the body of theloop after printing out the values you read.

unquiet mind
  • 1,082
  • 6
  • 11
0

it appears to be some memory addresses, because they are obviously not the actual numbers.

That's because you are printing the addresses!

printf("\n%d %d %d", column[i].col_1, &column[i].col_2, &column[i].col_3);

(apart from col_1, you/re printing the address)

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134