ANSI C 从文件中分离数据

ANSI C Separating the data from the file

我有一个文件,其中的数据类似于

zz:yy:xx.xxx [-]pp.pp

减号是可选的。我需要分离数据。我需要 [-]pp.pp 到 float 类型的下一个动作。我怎样才能用那部分数据制作一个浮点数组?

这里我打开了文件并打印了所有数据。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 2000
FILE *file;
int main()
{
    file = fopen("data.txt" , "r");
    int i,znak=0;
    char string[N];
    while ((znak = getc(file)) != EOF)
    {
    string[i]=znak;
    printf("%c",string[i]);
    i++;

    }
    return 0;
}

这样试试

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

#define FORMAT "%*[^:]:%*[^:]:%*[^: ] %f"

int main(void)
{
    FILE *file;
    float value;
    int size;
    float *array;
    // Open the file
    file = fopen("data.txt", "r");
    // This is really important
    if (file == NULL) {
        fprintf(stderr, "Can't open the file\n");
        return -1;
    }
    size = 0;
    // Count the number of entries in the file
    while (fscanf(file, FORMAT, &value) == 1) {
        size += 1;
    }
    // Reset the file position to the beginning
    rewind(file);
    // Allocate space for the array
    array = malloc(size * sizeof(*array));
    // And, ALWAYS check for errors
    if (array == NULL) {
        fprintf(stderr, "Out of memory\n");
        fclose(file);
        return -1;
    }
    // Extract the data from the file now
    for (int i = 0 ; i < size ; ++i) {
        fscanf(file, FORMAT, &array[i]);
    }
    // The file, is no longer needed so close it
    fclose(file);
    // Do something with the array 
    handle_array(size, array);
    // Free allocated memory
    free(array);
    return 0;
}