0

I do have a txt file which looks like this

10
41 220 166 29 151 47 170 60 234 49 

How can I read only the numbers from the second row into an array in C?

int nr_of_values = 0;
int* myArray = 0;
FILE *file;
file = fopen("hist.txt", "r+");
if (file == NULL)
{
    printf("ERROR Opening File!");
    exit(1);
}
else {
    fscanf(file, "%d", &nr_of_values);
    myArray = new int[nr_of_values];

    // push values from second row to this array
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43
Vlad Danila
  • 1,222
  • 3
  • 18
  • 38

1 Answers1

1

How can I read only the numbers from the second row into an array in C?

Ignore the first line by reading and discarding it.

You could use something like that:

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

int main(void)
{
    char const *filename = "test.txt";
    FILE *input_file = fopen(filename, "r");

    if (!input_file) {
        fprintf(stderr, "Couldn't open \"%s\" for reading :(\n\n", filename);
        return EXIT_FAILURE;
    }

    int ch;  // ignore first line:
    while ((ch = fgetc(input_file)) != EOF && ch != '\n');

    int value;
    int *numbers = NULL;
    size_t num_numbers = 0;
    while (fscanf(input_file, "%d", &value) == 1) {
        int *new_numbers = realloc(numbers, (num_numbers + 1) * sizeof(*new_numbers));
        if (!new_numbers) {
            fputs("Out of memory :(\n\n", stderr);
            free(numbers);
            return EXIT_FAILURE;
        }
        numbers = new_numbers;
        numbers[num_numbers++] = value;
    }

    fclose(input_file);

    for (size_t i = 0; i < num_numbers; ++i)
        printf("%d ", numbers[i]);
    putchar('\n');

    free(numbers);
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43