【问题标题】:fail to read a file with fscanf [closed]无法使用 fscanf 读取文件 [关闭]
【发布时间】:2016-04-06 13:16:39
【问题描述】:

我编写了以下代码,没有任何编译错误或警告。但是我的程序每次都崩溃?为什么以及如何解决这个问题?

代码

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

int main ()
{
  FILE *fp;

  int vertexIndex=0;
  float vertexTable[][2000]={0};
  int faceIndex = 0;
  int faceTable[][2000]={0};
  char lineHeader[128]={0};

  fp = fopen("C://Users//matt//Desktop//mannekeCoord.txt","r");

  if(fp == NULL) 
  {
     perror("Error in opening file");
     return(-1);
  }

  do
  {
    int res = fscanf(fp, "%s", lineHeader);
    if(res ==EOF)
      {break;}

    //vertex
    if ( strcmp( lineHeader, "v" ) == 0 ){
      fscanf(fp, "%f %f %f\n", &vertexTable[vertexIndex][0], &vertexTable[vertexIndex][1], &vertexTable[vertexIndex][2]);
      vertexIndex++;
    }

    //face 
    if ( strcmp( lineHeader, "f" ) == 0 ){
      fscanf(fp, "%d//%d %d//%d %d//%d %d//%d\n", &faceTable[faceIndex][0], &faceTable[faceIndex][1], &faceTable[faceIndex][2], &faceTable[faceIndex][3], &faceTable[faceIndex][4],  &faceTable[faceIndex][5], &faceTable[faceIndex][6],  &faceTable[faceIndex][7] );
      faceIndex++;
    }

  } while(1);

  fclose(fp);
  return 0;
}

这是它必须读取的文件内容的简短版本:

  v -0.999718 -1.004708 0.999546

  v -0.932863 -2.122097 -1.108066

  v -1.000000 1.000000 1.000000

  v -0.980325 0.671164 -1.031669

  v 0.094571 -2.805363 -1.376969

  v -0.437903 -2.617016 -1.306834

  f 728//48 782//48 785//48 751//48

  f 758//48 788//48 789//48 759//48

  f 727//48 783//48 782//48 728//48

  f 793//402 797//402 796//402 792//402

  f 790//48 794//48 797//48 793//48

  f 791//403 795//403 794//403 790//403

  f 783//404 791//404 790//404 782//404

  f 784//405 792//405 796//405 788//405

  f 789//48 797//48 794//48 786//48

  f 786//406 794//406 795//406 787//406

我使用这个网站编译它:http://www.onlinecompiler.net/

【问题讨论】:

  • 还有在线调试器吗?
  • 如果你不使用scanf,你可能会发现调试这个程序更容易。不开玩笑。 (还有很多其他原因不使用scanf,但目前最重要的是调试。)(要将文本转换为机器数,请使用strtol 用于整数和strtod 用于浮点数。)跨度>
  • 看看faceTable 并问问自己尺寸是否 a) 尺寸正确,b) 声明正确,c) 顺序正确...

标签: c file


【解决方案1】:

vertexTable 和 faceTable 的大小都为 2000 的 1,因此您正在写入未分配的内存,这会导致“未定义的行为”

【讨论】:

    【解决方案2】:

    这些声明是错误的:

    float vertexTable[][2000]={0};
    int faceTable[][2000]={0};
    

    你需要这个:

    float vertexTable[2000][3]={0};
    int faceTable[2000][8]={0};
    

    我希望您知道,如果顶点数或面数超过 2000,您仍然会遇到问题。

    【讨论】:

    • 当我怒不可遏时,malloc 真的是唯一的解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 2023-04-10
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多