ANSI C将数据与文件分开

时间:2016-10-23 11:53:59

标签: c ansi

我有一个包含

等数据的文件
zz:yy:xx.xxx [-]pp.pp

减号是可选的。我需要分开数据。我需要[-]pp.pp到float类型的下一个动作。如何使用该部分数据创建一个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;
}

1 个答案:

答案 0 :(得分:2)

试试这个

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