简体   繁体   English

在Visual C ++中读取.obj网格文件

[英]Reading .obj mesh file in Visual C++

I'm working on a program that takes in a Wavefront .obj file and eventually places it into OpenGL and displays the object. 我正在开发一个程序,该程序需要一个Wavefront .obj文件,并最终将其放入OpenGL并显示该对象。

Right now I'm just trying to read in a simple cube.obj file and print the contents. 现在,我只是试图读取一个简单的cube.obj文件并打印内容。 Its content is: 其内容是:

v -1.0 -1.0 -2.0 
v 1.0 -1.0 -2.0 
v 1.0 1.0 -2.0 
v -1.0 1.0 -2.0 
v -1.0 -1.0 -4.0 
v 1.0 -1.0 -4.0 
v 1.0 1.0 -4.0 
v -1.0 1.0 -4.0 
f 1 2 3 
f 3 4 1 
f 6 5 7 
f 5 8 7 
f 2 6 3 
f 7 3 6 
f 1 4 5 
f 4 8 5 
f 4 7 8 
f 4 3 7 
f 5 6 1 
f 6 2 1

I placed the cube.obj in the command-line args and did a check to see if it opened. 我将cube.obj放在命令行参数中,并进行了检查以查看它是否已打开。

FILE *fp;
fp = fopen(argv[1], "r");
if(fp == NULL)
    fprintf(stderr, "cat: can't open %s\n", argv[1]);
else
    printf("works");

cin.get();

It's not even opening. 甚至还没有开放。 Is there a better way to open the .obj file (as well as eventually print the contents of it?) 有没有更好的方法来打开.obj文件(以及最终打印该文件的内容?)

You have not provided enough information here, but it seems obvious that the problem is very likely the contents of argv[1] . 您在此处没有提供足够的信息,但是很明显问题很可能是argv[1]的内容。 What does the pointer at argv[1] point to? argv[1]上的指针指向什么? Don't assume, use your debugger and look at it. 不要假设,请使用调试器并对其进行查看。 I bet it's not what you think. 我敢打赌这不是你的想法。

You also don't consider the fact that your program may not have been launched with any arguments, meaning that argv[1] is reading past the end of a buffer. 您也不会考虑您的程序可能没有以任何参数启动的事实,这意味着argv[1]正在读取缓冲区的末尾。 This is tangential though. 这是切线的。

EDIT: 编辑:

Per your comment, you need to provide the full path of the file to fopen . 根据您的评论,您需要提供fopen文件的完整路径。 It should work if the file is in your running directory, but depending on your environemnt (VS is one) that may not be as simple as it sounds. 如果文件位于您的运行目录中,它应该可以工作,但是取决于您的环境(VS是其中之一),可能听起来并不那么简单。

I ran a test with a file foo.txt in my \\project\\debug directory, the same directory as my executable. 我在\\ project \\ debug目录(与可执行文件相同的目录)中使用文件foo.txt进行了测试。 It failed to open the file with a relative path, but succeeded with the full path. 它无法使用相对路径打开文件,但使用完整路径成功。

However, if I simply double clicked the executable in that directory it worked. 但是,如果我只双击该目录中的可执行文件,它就会起作用。 Apparently VS is doing something behind the scenes that is changing the working directory. 显然,VS在幕后做了一些更改工作目录的事情。

To use relative paths, right click the project -> Properties -> Debugging -> Working directory. 要使用相对路径,请右键单击项目->属性->调试->工作目录。 Set that to your output folder and you should be fine. 将其设置为输出文件夹,就可以了。

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

int main() {
    FILE *file;
    if(!(file = fopen("foo.txt", "r"))) {
        printf("no worky");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM