h101 h101 - 1 year ago 93
C Question

How to get all numbers from a file and input them into an array?

SO i can have a input file that can have either a space or a new line between each number within the file. An example of this could be:

2 3 4
4 3 2 3
2 3 1
5 4 3 2
2 5 4 2

How would i parse through the file and grab all of the elements and place them inside an array. Currently I have the following code:

#define FILE_READ "input.txt"

int main()

FILE * filp;
int count = 1;
char c;
filp = fopen(FILE_READ, "r");
if(filp == NULL)
printf("file not found\n");
while((c = fgetc(filp)) != EOF) {
if(c == ' ')
printf("numbers = %d\n", count);
return 0;
int myarray[count-1];

So how exactly would i push the numbers into the array at this point? I got the number of numbers in the file and created an array the size of the numbers. Now how exactly would i put the numbers into the array now?

Answer Source

This is a very simple thing to do, just use fscanf() to count how many values and then use malloc() to allocate space for them. Then, use fscanf() again to read the values into the array.

This might seem like a lot of work, but allocating space for every value is more. One optimization that can be worth the effort would be to allocate an estimate size array and then grow the array in multiples of the initial estimate using realloc() when you run out of space. This way, you reduce the number of allocations and at the same time you only loop through the values (reading from the file which is also expensive only once).

This is the easiest way I think

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

    FILE *file;
    int count;
    int value;
    file = fopen("input.txt", "r");
    if (file == NULL)
        return -1; // Error opening the file
    count = 0;
    while (fscanf(file, "%d", &value) == 1)
        count += 1;
    if (count > 0) {
        int *array;

        array = malloc(count * sizeof(*array));
        if (array == NULL) {
            return -1;
        count = 0;
        while (fscanf(file, "%d", &array[count]) == 1) {
            fprintf(stdout, "%d\n", array[count]);
            count += 1;
        // Use the array now and then
    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download