c - 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;
}```
解决方案
推荐阅读
- php - PHP cUrl 请求转义问题(HTTP 错误 400。请求格式错误。)
- vuejs2 - v-for 循环中的条件“@click”
- python - 正则表达式在链接中查找特定字母
- java - SERVLET_MAPPING Struts1 中的 .do 后缀到 Spring Boot 迁移
- javascript - Vue 组件仅在我在浏览器上打开控制台模式时加载
- javascript - 在最后一个参数上获取带有增量号的 api 请求
- ios - 尝试呈现其视图不在窗口层次结构中的 Xamarin_Forms_Platform_iOS_NavigationRenderer
- javascript - React - 如何取消过滤。()我的对象数组?
- java - 无法从通知中打开活动
- reactjs - 从库导入时,Invariant 失败:您不应该使用
外面