澄清一下——我是 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
最佳答案
由于您是“C 的初学者”,我想首先欢迎您使用一种非常严谨但有益的语言。不过,公平地说,我不认为编写操作系统代码的人是 C 语言的“初学者”。
我很乐意为您提供帮助,并在我们继续进行时更新此答案。我的第一个建议如下:
在执行文件操作(如打开文件)时,您总是应该做的第一件事就是检查执行结果!例如,如果您阅读 man page在 fopen()
上,您会看到 fopen()
将
return a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error.
因此,使用类似于以下代码的内容来确保您的文件按预期打开:
if (fp == NULL) {
printf("fopen did not work! Check errno %d\n", errno);
}
else {
printf("fopen workd!\n");
}
一旦您就实现上述代码的结果回复我,我将更新此答案。
关于C 程序无法访问 textile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36754042/