【问题标题】:Read co-ordinates from a txt files using C Program使用 C 程序从 txt 文件中读取坐标
【发布时间】:2009-06-24 09:02:00
【问题描述】:

我想使用 C 程序将 .txt 文件中大量点的笛卡尔坐标读入矩阵或某些此类数据结构中。

文件具有类型的内容

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

等等……

文件中有大约 4000 个这样的坐标。第一列表示 x 坐标,第二列表示 y,第三列表示 z 坐标。每行代表一个点。我最终想根据坐标进行一些计算。我只是对 C 中的文件处理有一个初学者级别的想法。

有什么想法吗??请尽快回复!

【问题讨论】:

  • 家庭作业?您希望我们为您编写代码吗?把你的尝试放在这里,问问到底是什么不起作用。
  • 那又怎样!它的纯编程问题就是堆栈溢出的意义——增加程序员的知识。这家伙想学习如何做某事。

标签: c parsing matrix


【解决方案1】:

首先你可能想使用一个结构来存储每个点

typedef struct {
   float x;
   float y;
   float z;
} Point;

然后将文件读入点数组

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

【讨论】:

  • 在栈上声明 12000 个浮点数是非常不明智的。
  • 那里,改为使用堆内存:P
【解决方案2】:

使用 sscanf 和 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);
}

【讨论】:

    【解决方案3】:

    我会说fscanf? (举个例子)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-04
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      相关资源
      最近更新 更多