从文本文件中读取并使用GNU libplot绘图

时间:2014-03-10 01:11:52

标签: c

我制作了一个从文件中读取的程序,并按字母顺序对文件中包含的名称进行排序。该文件包含行星名称,质量,大小,颜色,主体,位置x,y,z和速度x,y,z。我现在正试图使用​​这个文件绘制每个星球,但我不确定如何去做。我正在使用GNU libplot来绘制行星。我想我需要使用循环和fscanf来获取x和y坐标(现在可以省略Z)来绘制每个行星。

这是我目前的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAMES 20

struct planets{ //sets up initial characters and doubles to place into body.
  char primaryBody[NAMES];
  char name[NAMES];
  char color[NAMES];
  double mass;
  double size;
  double posx, posy, posz;
  double velx, vely, velz;
};

struct planets body[100];

int readData(FILE* fd){ //This reads the file solarsystem.txt and fills array

int current = 0;
char line[201];
char cmpline[2] = "#";

do{
    fgets(line, 200, fd); // Makes sure that the number of bytes written dont overflow   your character.
}while((strlen(line)<2)||(strncmp(line, cmpline, 1))==0);
sscanf(line, "%s %lf %s %lf %s", body[current].name, &body[current].mass, body[current].color, &body[current].size, body[current].primaryBody);
fscanf(fd, "%lf %lf %lf", &body[current].posx, &body[current].posy, &body[current].posz);
fscanf(fd, "%lf %lf %lf", &body[current].velx, &body[current].vely, &body[current].velz);
current++;

while(!feof(fd)){//Runs the loop until the end of the file is met.
  fscanf(fd, "%s %lf %s %lf %s", body[current].name, &body[current].mass, body[current].color, &body[current].size, body[current].primaryBody);
  fscanf(fd, "%lf %lf %lf", &body[current].posx, &body[current].posy, &body[current].posz);
  fscanf(fd, "%lf %lf %lf", &body[current].velx, &body[current].vely, &body[current].velz);
  current++;
}
  return current;
}

void sortNames(int planetNames){ //traditional bubble sorting code, with slight  modification.

struct planets temp[1];

for(int i=0; i<(planetNames);i++){
  for(int j=0; j<(planetNames-1); j++){
    if (strcmp(body[j].name, body[j+1].name)>0){
      temp[0] = body[j];
      body[j] = body[j+1];
      body[j+1] = temp[0];
    }
  }
}

void printBodies(int sortNames){// code to print out the sorted file.    
  int planetNames = sortNames;

  printf("Name     Mass       Color  Size  Primary Body\n");
  printf("_____________________________________________\n");

  for(int i=0; i<(planetNames); i++){
    printf("%-8s %1.4E %-6s %.2lf  %s\n", body[i].name, body[i].mass, body[i].color, body[i].size, body[i].primaryBody);
  }
}

int main(int argc, char *argv[]){/*runs the different structs, and if file not available, will tell the user.*/
  FILE *fd;
  fd = fopen (argv[1], "r");

  if(!fd){
      printf("File not available, or user did not type file name.\n");
      return 1;
  }
  int planetNames=readData(fd);
  sortNames(planetNames);
  printBodies(planetNames);
  findMax(planetNames);

  return 0;
}

0 个答案:

没有答案