0
FILE *pFile;
pFile = fopen("address01", "r");
int  yup[8];
int*  array[7];

for (int i = 0;i < 7; i++) {
    while (!feof(pFile)) {
        fgets(yup, 8, pFile);
        puts(yup);     //It DOES print each line
        array[i] = yup;
    }
}
fclose(pFile);
printf("First: %d",array[0]);     //I want it to print the first thing in the file, but I get a
                                  //crazy number. It should be 10.
printf("Second: %d",array[1]);    //I want it to print the 2nd thing in the file, but I get a
                                  //crazy number. It should be 20
                                  //etc.

Essentially, I want to be able to select any number in my array for later manipulation.

Contents of address01:

10

20

22

18

E10

210

12

Dweeberly
  • 4,668
  • 2
  • 22
  • 41

1 Answers1

0

The prototype of fgets is

char * fgets ( char * str, int num, FILE * stream );

You are using an int* (int yup[8]) where you should be using a char *.

If the address01 file you are reading is text, then you need to change your definition of yup. If your file is binary you need to provide information on what the format of your binary is.

The array you have defined is a pointer to an int array, but you need an array of char *. The other problem is that your yup variable is always pointing to the same address, so you are just overwriting the same memory. You need to allocation (malloc()) your yup variable before each fgets in order for each read to be placed in new memory.

Something like this:

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

int main(void) {
    FILE *pFile;
    pFile = fopen("address01", "r");
    char *yup;
    char *array[7];

    for (int i = 0;i < 7; i++) {
        yup = (char *) malloc(8);
        if (yup == NULL) {
            // this indicates you are out of memory and you need to do something
            // like exit the program, or free memory
            printf("out of memory\n");
            return 4; // assuming this is running from main(), so this just exits with a return code of 4
            }
        if (feof(pFile)) {
            break; // we are at the end, nothing left to read
            }
        fgets(yup, 8, pFile);
        puts(yup); 
        array[i] = yup;
        }
    fclose(pFile);
    }
Dweeberly
  • 4,668
  • 2
  • 22
  • 41