Mateo Mateo - 1 month ago 7
C Question

ANSI C Separating the data from the file

I have a file with data like

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


The minus is optional. I need to separate the data. I need that
[-]pp.pp
to the next actions in float type. How can I make an float array with that part of data?

Here I opened the file and printed all data.

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

Answer

Try like this

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