Umar
Umar

Reputation: 55

reading file with float values

I have a question reading a txt file containing float value. I have seen some tutorials about reading txt files and all of them soo far are either using fgetc or fgets to read the content of files. I was looking for some similar function for float as the contents of my file is float. Is there a some way to read file containing float or i use these functions to break for flaot and read each as a character and then print that value ?

Upvotes: 2

Views: 2549

Answers (4)

Jay
Jay

Reputation: 9656

You could use fscanf, for example:

#include <stdio.h>

int main() {
    float var;
    FILE *file;
    file = fopen("input","r");
    fscanf(file, "%f", &var);
    printf("the value is %f\n",var);
    fclose(file);
    exit(0);
}

fscanf takes two initial parameters, a pointer to a FILE structure and a string format just like that of printf. Then you can add other parameters, which will be pointers to the variables you are reading. It will return the number of items successfully read.

There are other ways. If your input file has a nontrivial structure, you could try parsing it with some tools like flex and bison. Flex is a tokenizer: it will help you read items from a file, splitting them (strings, numbers, identifiers, special symbols -- in any way you specify). Bison is a parser generator: you describe a grammar of tokens, and it will generate a parser for you.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

Read each line using fgets, then depending on how the lines are formatted you could use sscanf() to parse the values, or strtod().

Upvotes: 2

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

If you are reading from just one text file, you may use I/O redirection.

#include <stdio.h>

    int main() {
        float a;
        scanf("%f", &a);
        return 0;
    }

If your executable file name is say abc.exe or simply abc, run as:

abc < in.txt

Upvotes: 0

Spikatrix
Spikatrix

Reputation: 20244

Use fscanf like this

fscanf(myfile,"%f",&myfloat);

Upvotes: 1

Related Questions