Search code examples
carraysstdin

Redirecting a file from stdin, using fgets() to read information to array


int main() {
#define MEMSIZE 100
    int memory[MEMSIZE] = {0};
    int i = 0;
    char *temp = malloc(sizeof(100));

    fgets(temp, MEMSIZE, stdin);

    for (i = 0; i < (sizeof(memory)/sizeof(int)); i++) {
        memory[i] = temp[i];
    }

    for (n = 0; n < 10; n++) {    // Print contents
        printf("%d - %d\n", n, memory[n]); 
    }
}

So today I have what seems to be a very simple question. I am taking a file from stdin, using:

./a.out < filename

My main goal is to take in the numbers provided in the file, and store them into a 1 dimensional array. My current use of fgets() works correctly, reading in line one and copying those elements into my 1D array (their ASCII values converted to int). Now, to read in my next lines, if I call fgets() again, the next line is read but it is then stored in the same place as the first values, thus overwriting them in my array in position 0-3. These values need to be stored successively in my array until EOF.

The file is in the format:

1234
5678
... 

Solution

  • #include <stdio.h>
    
    #define MEMSIZE 100
    
    int main() {
        int memory[MEMSIZE] = {0};
        int i,n;
        for (i = 0; i <MEMSIZE; i++){
            if(fscanf(stdin,"%d", (memory+i))==EOF){
                break;
            }
        }
       //i is the number of ints you got
       for (n = 0; n < i; n++) {    // Print contents
       printf("%d - %d\n", n, memory[n]); 
       }
       return 0;
    }
    
    1. I dont see a reason to use dynamic allocation over here as a temp variable.

    2. If the file is list of numbers, just read as a number, no need for fgets over here, if you still want to read it as a string, have a look at atoi func

    3. sizeof(memory)/sizeof(int)= (sizeof(int)*MEMSIZE)/sizeof(int)= MEMSIZE

    4. You shouldn't just loop MEMSIZE times, you need to know when it EOF

    5. I dont know why you assumed in the printing loop that 10 is enough, i changed it to i which is number of elements

    6. You didnt define n

    I hope that i helped.