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