C++ fscanf_的缓冲区溢出异常
在openGL初学者教程之后,我已经完成了自己的.OBJ文件加载程序的编写。在编写之后,通常会遵循编译过程,这在C++中是令人厌烦和讨厌的。我在我的一个方法中遇到了一个未处理的异常,下面是代码:C++ fscanf_的缓冲区溢出异常,c++,C++,在openGL初学者教程之后,我已经完成了自己的.OBJ文件加载程序的编写。在编写之后,通常会遵循编译过程,这在C++中是令人厌烦和讨厌的。我在我的一个方法中遇到了一个未处理的异常,下面是代码: float* Loader::LoadObj(const char* filePath){ //Declaration of v, vt and vn temporary container buffers for parsing vector<glm::vec3> vertcies; ve
float* Loader::LoadObj(const char* filePath){
//Declaration of v, vt and vn temporary container buffers for parsing
vector<glm::vec3> vertcies;
vector<glm::vec2> uvs;
vector<glm::vec3> normals;
vector<fvert> facevertcies;
//open the file
FILE* objFile;
fopen_s(&objFile, filePath,"r");
if( objFile == NULL )
{
printf("Impossible to open the file ! Are you in the right path ?\n");
}
char line[128]; // where to store the first string read from each line
//other containers
glm::vec3 vertex;
glm::vec2 uv;
glm::vec3 normal;
fvert fv1,fv2,fv3;
// for each line in the obj file
while(true)
{
// read the first word of the line
int lineId = fscanf_s(objFile,"%s",line);
if (lineId == EOF)
break;
// parse line by line
if ( strcmp( line, "v" ) == 0 )
{
fscanf_s(objFile, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
vertcies.push_back(vertex);
}
else if ( strcmp( line, "vt" ) == 0 )
{
fscanf_s(objFile, "%f %f\n", &uv.x, &uv.y);
uvs.push_back(uv);
}
else if ( strcmp( line, "vn" ) == 0 )
{
fscanf_s(objFile,"%f %f %f\n", &normal.x, &normal.y, &normal.z );
normals.push_back(normal);
}... //method continues}}
额外的问题:我在这里还读到,我的代码可以通过使用char*而不是固定的char数组来改进,并将%ms传递给fscanf,后者动态地为存储分配内存。有人能告诉我,如何在我的代码中实现它吗?这种可能性很吸引人,尽管事实上我甚至不能让那该死的原版运行。非常感谢那些能够提供帮助的人
int lineId = fscanf_s(objFile,"%s",line);
可能应更改为:
int lineId = fscanf_s(objFile,"%s",line,sizeof(line));
安全版本就到此为止…:)
可能应更改为:
int lineId = fscanf_s(objFile,"%s",line,sizeof(line));
安全版本就到此为止…:)技术上,FSCANF不是C++函数。这是一个C函数。您可以使用和而不是
文件
(和相关函数)。如果我没记错的话,*.obj是一组由空格分隔的数字/字符串。使用IoSt流来代替类似的东西,而不是使用C样式的函数,处理缓冲区溢出,将更容易。技术上,FSCANF不是C++函数。这是一个C函数。您可以使用和而不是文件
(和相关函数)。如果我没记错的话,*.obj是一组由空格分隔的数字/字符串。使用iostreams而不是使用C风格的函数和处理缓冲区溢出会更容易阅读这样的内容。非常感谢!这管用!有趣的是我以前试过,但没有。我不认为这适用于char*和%ms,因为它的大小尚未指定。我不能投票支持你的答案,因为我缺乏声望。我一到15岁就给你学分。非常感谢!这管用!有趣的是我以前试过,但没有。我不认为这适用于char*和%ms,因为它的大小尚未指定。我不能投票支持你的答案,因为我缺乏声望。我一到15岁就给你学分。