首页 > 解决方案 > C文件阅读器每隔一行跳过

问题描述

我的目标是在 C 中加载一个 .obj 文件,但我的问题是 fscanf 似乎跳过了每一行,而不是顺利地读取它。我没有收到任何错误信息。我检查了其他问题,但我没有两次调用 fscanf,或者写了其他文件阅读器中不存在的任何内容。

例如,文件中的 4 行如下所示:

v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000

但输出将是:

read from file: v, 1.000000, -1.000000, 1.000000
read from file: v, -1.000000, -1.000000, -1.000000

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/* Primary vector function */
struct vec3d {
  float x;
  float y;
  float z;
};

/* Triangle structure of 3 vectors */
struct triangle {
  struct vec3d p1;
  struct vec3d p2;
  struct vec3d p3;
};

/* function to load an object file */
int main (){

    struct vec3d verts[256];
    struct triangle tris[256];
    int lastVertIndex = 0;
    int lastTriIndex = 0;

    FILE* fp;
    fp = fopen("cube.obj", "r");
    if (fp == NULL){
        perror("Error while opening the file.\n");
        exit(EXIT_FAILURE);
    }

    char singleLine[128];

    while(!feof(fp)){
        fgets(singleLine, 128, fp);
        if(singleLine[0] == 'v' && singleLine[1] == ' '){
          struct vec3d v;
          char junk[2];
            
          fscanf(fp, "%s %f %f %f", &junk, &v.x, &v.y, &v.z);
          printf("read from file: %s, %f, %f, %f\n", junk, v.x, v.y, v.z);
          verts[lastVertIndex].x = v.x;
          verts[lastVertIndex].y = v.y;
          verts[lastVertIndex].z = v.z;
          lastVertIndex++;
        }

        if(singleLine[0] == 'f' && singleLine[1] == ' '){
          int f[3];
          char junk[2];
          fscanf(fp, "%s %f %f %f", &junk, &f[0], &f[1], &f[3]);
          tris[lastTriIndex].p1 = verts[f[0] - 1];
          tris[lastTriIndex].p2 = verts[f[1] - 1];
          tris[lastTriIndex].p3 = verts[f[2] - 1];
          lastTriIndex++;
        }
    };
    fclose(fp);
    return 0;
}```

标签: cfilescanf

解决方案


推荐阅读