'Is there any way to read integer from txt file and store separately in to variables? In C

So I am new to C programming and I wanted to know if there is any way of reading a txt file into a C program and store the integers separately.

An Example of the input file :

300 20 40 35 59 288 29 04 82

What I am trying to do is the take the first number in the file and store it to a variable "first_num = 300"

second number storing in variable "second_Num = 20"

However from the third number to the end would be stored in a variable called "remaining_num = 40 35 59 288 29 04 82"

This way i can print or use them separately.

This is the code i have so far

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

int main()
{

FILE *fp;
int  first_num , second_num , remaining_num ;
char fileName[100];

printf("Enter the file name to be read from: ");
scanf("%s", fileName);


fp=fopen(fileName,"r");
fscanf(fp,"%d", &first_num);
fscanf(fp,"%d", &second_num );
fscanf(fp,"%d", &remaining_num );

printf("%d\n", first_num);
printf("%d\n", second_num );
printf("%d\n", remaining_num);


Solution 1:[1]

If you want to hold an arbitrary number of integers, you will need to have some type of container that will do that for you. The base language does not provide such data structures, and you have to build them yourself. For this case, you can do something like:

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

struct int_buf {
    int *data;
    size_t length;
    size_t capacity;
};

void
push(struct int_buf *d, int t)
{
    while( d->capacity <= d->length ){
        d->capacity += 128;
        d->data = realloc(d->data, sizeof *d->data * d->capacity);
        if( d->data == NULL ){
            perror("realloc");
            exit(EXIT_FAILURE);
        }
    }
    d->data[d->length++] = t;
}

int
main(int argc, char **argv)
{
    int  first_num, second_num;
    int t;
    const char *path = argc > 1 ? argv[1] : "stdin";
    FILE *fp = argc > 1 ? fopen(path, "r") : stdin;
    if( fp == NULL ){
        perror(path);
        return EXIT_FAILURE;
    }
    if(
        fscanf(fp, "%d", &first_num) != 1
        || fscanf(fp, "%d", &second_num) != 1
    ){
        fprintf(stderr, "Invalid input\n");
        return EXIT_FAILURE;
    }
    struct int_buf remaining_num = {NULL, 0, 0};
    while( fscanf(fp, "%d", &t) == 1 ){
        push(&remaining_num, t);
    }

    printf("%d\n", first_num);
    printf("%d\n", second_num );
    for( size_t i = 0; i < remaining_num.length; i++ ){
        printf("%d\n", remaining_num.data[i]);
    }
    free(remaining_num.data);
    return 0;
}

Note that scanf is a terrible tool, and even something as simple as this will exhibit undefined behavior on certain inputs. Do not use scanf.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 William Pursell