如何解决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
这是我的代码:
#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\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,&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;
}```
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。