0

Im trying to read float values line by line from a text file and store it in an array. I have not been able to figure this out yet. Below is my code and Im hoping someone can help me. Ive tried with "fscanf" and "fgets". Can anyone show me the best way to accomplish this?

Here's my current full code, but it still doesn't appear to be working properly.

int main(int argc, char *argv[]) {

int num = atoi(argv[1]);
char *filename = argv[2];

float *num_array = (float *)malloc(num * sizeof(float));

if(argc < 3){
    printf("No / not enough arguments specified!\n");
    printf("Usage: Program #values input_file_name\n");
    exit(0);
}

if(sscanf(argv[1],"%d",&num) != 1){
    printf("Argument #2 is not an integer!\n");
    exit(0);
}


printf("Number of values to be read: %d\n", num);
printf("You want to read the values from %s: \n", filename);

/*
 * This code for file existance does not appear to be working, not sure why!
 */
FILE *fp = fopen(filename, "r");
if(!fp){
    puts("Could not open file!");
    return(1);
}

int i = 0;

while(!feof(fp) && i < num){
    fscanf(fp, "%f\n", &num_array[i]);

    i++;
}
printf("%f",num_array[0]);
fclose(fp);

}

choff5507
  • 11
  • 2

1 Answers1

-1

You can use fscanf to read in floating point numbers directly, without the need to call atof. Assuming you have a file called numbers.txt with the content:

3.14159
2.877
91.3
-1392.22
0.1234

The following program will read them in and store them in an array of floats. Take care though, the array is only large enough to hold 5 numbers. If you need a variable amount of numbers, then you must dynamically allocate an array to hold them.

#include <stdio.h>
#include <string.h>

int main(void) {
    int i = 0;
    float numbers[5] = {0};

    FILE *fp = fopen("numbers.txt", "rb");
    if (!fp) {
        puts("could not open file");
        return 1;
    }

    for (;;) {
        if (fscanf(fp, "%f\n", &numbers[i]) != 1) {
            break;
        }
        i++;
    }

    fclose(fp);
    return 0;
}
hgs3
  • 525
  • 3
  • 6