Read co-ordinates from a txt files using C Program

2019-08-07 04:00发布

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!

标签: c parsing matrix
3条回答
老娘就宠你
2楼-- · 2019-08-07 04:32

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);
查看更多
霸刀☆藐视天下
3楼-- · 2019-08-07 04:44

I'd say fscanf ? (an example is given)

查看更多
家丑人穷心不美
4楼-- · 2019-08-07 04:46

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);
}
查看更多
登录 后发表回答