ProtectorOfUbi
ProtectorOfUbi

Reputation: 327

how do i read file of ints and store in variables in c

Ive just started c programming.

I would like to read a file of ints which are in a text file in the format

    int1(space)int2(space)int3
    int4(space)int5(space)int6
    int7(space)int8(space)int9

data file example (actually has 25 million lines)

1000002 1 55
1000002 1000006 33
1000002 1000007 8

i am trying to read the numbers and each line i would like to store the 3 ints into a separate variable so i can create a struct with 3 ints per struct. I have a function to create the structs however i don't know how to read the numbers in line by line then assign each 3 ints into a temp variable.

I will be using dynamic allocation to store the structs so just array as temp storage

    FILE *fp = fopen("uboss.txt", "r");
    //char text[255];
    int i = 1;
    int a = 1;
    int numberArray[9999];
    int tmpUI = 0;
    int tmpAI = 0;
    int tmpPC = 0;

    if (fp == NULL)
    {
        printf("Error Reading File\n");
        exit (0);
    }

   while (!feof(fp))
   {
        fscanf(fp, "%d ", &numberArray[i]);
        printf("Number %d: %d\n",i,numberArray[i]);
        tmpUI = numberArray[a];
        tmpAI = numberArray[a+1];
        tmpPC = numberArray[a+2];
        i++;
   }

    fclose (fp);

Upvotes: 1

Views: 818

Answers (2)

user411313
user411313

Reputation: 3990

Its very simple if you know how fscanf works (and returns):

while( fscanf(fp, "%d%d%d", &tmpUI, &tmpAC, &tmpPC) == 3 )
{
  ...
}

Upvotes: 0

chqrlie
chqrlie

Reputation: 144969

You are not the only one asking about this assignment. Try a simpler approach:

  • In a loop, read each line with fgets(),
  • Then scan the line for 3 integers with sscanf(str, "%d%d%d", &a, &b, &c); and check the return value, it should be 3.
  • Finally deal with the values: store them, test them, output them...

There might be extra problems to watch for:

  • What if the input file contains non numeric values?
  • What if the values are larger than can fit in the int type.

Upvotes: 3

Related Questions