如何用C语言从Wavefront .obj文件中提取面的首个顶点索引
实现方案
你已经拆分得到了数字/数字/数字格式的面字段,直接用sscanf()格式化读取即可快速提取第一个数值,sscanf读取整数时遇到/这类非数字字符会自动终止,不需要额外手动拆分字符串。
同时你原代码里统计行数的逻辑存在未定义行为:字符变量ch没有初始化就判断ch != EOF,顺便也做了修正。
修改后的完整代码如下:
#include <stdio.h> #include <string.h> //lazy wavefront obj file parser int main(){ FILE *fp = fopen("head.obj", "r"); if (!fp) { // 增加文件打开失败判断,避免运行崩溃 perror("fopen failed"); return 1; } //find the number of lines in the file int no_lines = 0; int ch; // EOF是int类型,需要用int存储getc的返回值 while((ch = getc(fp)) != EOF){ if(ch == '\n') no_lines++; } printf("number of lines: %d\n", no_lines); //set seek point to start of the file fseek(fp, 0, SEEK_SET); //get the faces and parse them char line[100]; while(fgets(line, sizeof(line), fp) != NULL){ if(line[0] == 'f'){ int first_item = 1; // 标记当前行第一个面索引,避免输出开头多逗号 //split the line at spaces char *s = strtok(line, " "); while(s != NULL){ if(*s != 'f'){ int vertex_idx; // 直接读取第一个整数,遇到/自动停止读取 sscanf(s, "%d", &vertex_idx); if (first_item) { printf("%d", vertex_idx); first_item = 0; } else { printf(", %d", vertex_idx); } } s = strtok(NULL, " "); } printf("\n"); // 单行走面数据输出完成后换行 } } fclose(fp); return 0; }
运行后就会输出你期望的格式,每一行面对应的顶点索引用逗号分隔:
1202, 1220, 1200 1200, 1220, 1198 1201, 1200, 1199 1201, 1202, 1200
如果需要拿到数值做后续处理而非直接打印,把vertex_idx存到自定义数组中即可。
内容的提问来源于stack exchange,提问作者iwrestledthebeartwice
相关产品推荐
相关产品推荐

