使用C程序一个txt文件阅读坐标 [英] Read co-ordinates from a txt files using C Program

查看:300
本文介绍了使用C程序一个txt文件阅读坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个C程序从.txt文件中读取一个大点的集合笛卡尔坐标到矩阵或类似的数据结构。

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.

该文件具有类型的内容

023    435    1.0
23.5   12.5   0.2
: :     : :   : :
: :     : :   : :

等等...

有该文件中约4000,例如坐标。第一列表示的x坐标,第二列y和第三列z坐标的。每一行再presents点。我最终想要做基于所述坐标一些计算。我只是有文件的C.处理的初学者水平的想法

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!

推荐答案

使用sscanf和GNU函数getline。

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);
}

这篇关于使用C程序一个txt文件阅读坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆