kachilous
kachilous

Reputation: 2529

How to read data from a text file in C

I have the following text file:

ax: 0
ay: -9.8
x: 0
y: 50
vx: 8.66
vy: 6

I want to read only the numerical values to be used for computations. Is there a way to ignore the strings and just read the values as floats?

Here is what I have so far:

FILE *fp; 
FILE *fr;

fr = fopen("input_data", "rt");
fp = fopen("out_file.txt", "w");  

if(fr == NULL) {
    printf("File not found");
}

if(fp == NULL) {
    printf("File not found");
}    

float ax = 0, ay = 0,
      x = 0, y = 0,
      vx = 0, vy = 0,
      time = 0, deltaTime = 0; 

fscanf(fr, "%f %f %f %f %f %f %f %f\n",
       &ax, &ay, &x, &y, &vx, &vy, &time, &deltaTime);

printf("%f %f %f %f %f %f %f %f\n",
       ax, ay, x, y, vx, vy, time, deltaTime); 

Upvotes: 3

Views: 13122

Answers (2)

detunized
detunized

Reputation: 15299

Use this instead:

fscanf(fr, "ax: %f ay: %f x: %f y: %f vx: %f vy: %f", &ax, &ay, &x, &y, &vx, &vy);

Upvotes: 8

Seth Robertson
Seth Robertson

Reputation: 31471

Use %s where the strings go.

Sample code :

#include <stdio.h>

main()
{
  FILE *fp;
  FILE *fr;
  char junk[100];

  fr = fopen("/tmp/x.txt", "rt");

  if(fr == NULL){ printf("File not found");}

  float ax = 0, ay = 0, x = 0, y = 0, vx = 0, vy = 0, time = 0, deltaTime = 0;

  fscanf(fr, "%s %f %s %f %s %f %s %f %s %f %s %f\n", junk, &ax, junk, &ay, junk, &x, junk, &y, junk, &vx, junk, &vy);

  printf("%f %f %f %f %f %f\n", ax, ay, x, y, vx, vy);

}

Upvotes: 1

Related Questions