C程序无法访问纺织品

时间:2016-04-20 20:02:13

标签: c fopen exc-bad-access scanf

为了说清楚 - 我是C的初学者。

当我的程序运行时(使用Xcode),没有值对应于“resultfortran.txt”中的值。相反,它们变得非常小,非常大或为零(看起来随机)。例如,变量n变为0,即使“resultfortran.txt”中的第一行是10.变量min和max也变得非常小(并且不会得到第2行和第3行的值)。

我整天搜索网络,并问我的同学们。如果感兴趣,我在打开文件的行上得到错误“EXC_BAD_ACCESS”,但该错误(有些怎么样?)消失了。是的,“resultfortran.txt2与main.m在同一个文件夹中。

程序的开头如下所示:

#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <GLUT/glut.h>
#include <OpenGL/OpenGL.h>
#include <Cocoa/Cocoa.h>


static void draw( void )
{
int n,i,j;
float step,min,max,x,y,scaled;
float matrix[1000][1000];

FILE *fp; //reads input file
fp=fopen("resultfortran.txt", "r");
fscanf(fp,"%d",&n); //Gives n the value of the first line.
step=(1.0/n); //Defines step size
fscanf(fp,"%f",&min); //Gives min the value of the second line.
fscanf(fp,"%f",&max); //Gives max the value of the third line.

for (i=0;i<n+1;i=i+1)
{

    for (j=0;j<n+1;j=j+1)
    {
        fscanf(fp,"%f",&matrix[i][j]);
    }
}
... not finished here ...

文件“resultfortran.txt”的第一行(来自fortran脚本的输出)如下所示:

10
0.00000000
0.500000000
0.0000000000
0.0025000002
0.0100000007
0.0225000009
0.0400000028
0.0625000000
0.0900000036
0.1224999949
0.1600000113
0.2024999857
0.2500000000
0.0025000002
0.0050000008
0.0125000002

1 个答案:

答案 0 :(得分:1)

由于你是“C语言的初学者”,我想首先欢迎你使用一种非常严谨但有益的语言。虽然,公平地说,我不会认为编写操作系统代码的人是C中的“ beginner”

我很乐意帮助您并在我们继续时更新此答案。我的第一个建议如下:

在执行文件操作(如打开文件操作)时,总是应该做的第一件事就是检查执行结果!例如,如果您阅读fopen()上的man page,则会看到fopen()

  

返回一个FILE指针。否则,返回NULL并将errno设置为   表明错误。

因此,请使用类似于以下代码的内容,以确保您的文件按预期打开:

if (fp == NULL) {
    printf("fopen did not work! Check errno %d\n", errno);
}
else {
    printf("fopen workd!\n");
}

一旦您回复上述代码的实施结果,我将更新此答案。