从C数组中的txt文件第二行读取数字

时间:2018-11-14 14:29:29

标签: c arrays file row

我确实有一个看起来像这样的txt文件

10
41 220 166 29 151 47 170 60 234 49 

如何只将第二行中的数字读入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
}

1 个答案:

答案 0 :(得分:1)

  

如何只将第二行中的数字读入C语言的数组中?

通过读取并丢弃第一行来忽略它。

您可以使用类似的东西:

#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);
}