psimeson
psimeson

Reputation: 205

C Programming reading file

I am trying to write a very simple code to read a file. However in that file I have M_PI/2, which is pi/2. When my code reads that file it spits M_PI/2 as 0.000. How do I make my program to make it read as pi/2.

#include<stdio.h>
#include<math.h>
#include<stdlib.h>

int main()
{
    FILE *infile;
    infile = fopen("./test.txt","r");
    double p;


    fscanf(infile, "%lf", &p);

    printf ("%lf\n", p);
}


test.txt
M_PI/2

Upvotes: 0

Views: 163

Answers (2)

You want in fact to read expressions not numbers. So you want to evaluate these expressions (in some environment, which defines what is the meaning -or binding- of variables).

So if you insist on keeping your requirement, you want an evaluator, i.e. an interpreter.

A possible way would be to embed some existing interpreter, like Lua, Guile, etc.

Otherwise, you want a parser for your expression language (which you should specify on paper, including its formal syntax -e.g. using BNF- and its semantics), and an evaluator for the parsed ASTs. Formally speaking your M_PI looks like a mathematical variable, and has its value in some environment.

If you want to go that route, read some tutorial textbook on interpreter and compiler implementations. The wikipage on recursive descent parser is explaining how to do something similar to your needs. Google also on arithmetic expression evaluator, you'll get a lot of relevant hits.

The documentation on GNU bison (a parser generator, sometimes called a compiler-compiler) contains a section: §2.2 infix notation calculator which looks similar to your needs.

Upvotes: 1

Caleb
Caleb

Reputation: 124997

You'll need to read the contents of the file and evaluate it yourself. M_PI isn't a number outside of the context of a programming environment, and likewise the division operator / is really just a slash unless something interprets it as division. So, you'll need to create some sort of evaluator to feed the contents of the file to.

When you write M_PI/2 in your C source code you get π/2 because the compiler knows the M_PI is defined in math.h as π (an approximation of π, really), and it knows about the division operator. You haven't written a compiler or anything that can evaluate M_PI/2 the way you want, though, so you just get the contents of the file as they're written into the file.

The easiest way to get what you want when you read the file is to store the value that you want, i.e. 1.5707963267949, in the file. fscanf() will then read the value and properly interpret it as a float, since that's what you told it to read in your format string.

Upvotes: 2

Related Questions