Read co-ordinates from a txt files using C Program
Question
I want to read cartesian coordinates of a large set of points from of a .txt file into a matrix or some such data structure using a C program.
The file has contents of the type
023 435 1.0
23.5 12.5 0.2
: : : : : :
: : : : : :
and so on...
There are about 4000 such co-ordinates in the file. First column indicates the x-coordinate, second column y and the third column z coordinates. Each row represents a point. I ultimately want to do some computations based on the co-ordinates. I just have a beginners' level idea of File Handling in C.
Any ideas?? Kindly reply asap!
Solution
Using sscanf and GNU getline.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#define MAX 5000
typedef struct coord
{
float x;
float y;
float z;
} coord;
int main(int argc, char *argv[])
{
if(argc != 2)
exit(1);
char *filename = argv[1];
char *line = NULL;
int n = 0;
FILE *coordFile = fopen(filename, "r");
coord *coords = malloc(sizeof(coord) * MAX);
if(coords == NULL)
exit(3);
int i = 0;
while(getline(&line, &n, coordFile) != -1 && i < MAX)
{
int items = sscanf(line, "%f %f %f", &coords[i].x, &coords[i].y, &coords[i].z);
if(items != 3)
exit(2);
i++;
}
fclose(coordFile);
}
OTHER TIPS
First you might want to use a structure to store each point
typedef struct {
float x;
float y;
float z;
} Point;
Then read the file into an array of points
Point *points = malloc(4000 * sizeof *points);
FILE * fp;
fp = fopen ("myfile.txt", "r");
int index = 0;
while(fscanf(fp, "%f %f %f", &points[index].x, &points[index].y, &points[index].z) == 3)
index++;
close(fp);
I'd say fscanf ? (an example is given)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow