[Solved] How to read a data point from a text file in C


if you have the line already, it’s easiest to use sscanf() to do this:

long a, b;

if(sscanf(line, "%ld,%ld", &a, &b) == 2)
{
  /* Successfully parsed two long integers, now store them somewhere I guess. */
}

Note that it’s a good idea to check the return value of sscanf(), this protects you from wrongly accepting illegal data and getting undefined results.

You can do it in multiple steps too if you need more control, as @dasblinkenlights suggested. You can use strtol() to parse the first number from the start of the line, then if that succeeds look for the comma, and then parse the second number. It can be faster than sscanf(), but I wouldn’t expect too much for something this simple.

3

solved How to read a data point from a text file in C