【发布时间】:2016-12-02 15:42:51
【问题描述】:
我目前正在编写下面的 C 代码。我需要在fclose 之后访问while 循环之外的数组。 blackfin ADSP 内核似乎每次运行时都会崩溃。我将需要它进一步执行 FFT。请帮忙!
#include <stdlib.h>
#include <stdio.h>
#include <flt2fr.h>
#include <fract_math.h>
#include <math_bf.h>
#include <complex.h>
#include <filter.h>
int main()
{
int n = 1024;
long int dat1[n];
FILE *file1;
fract16 *m;
int i;
// file1 open and read the values
file1 = fopen("0.dat", "r");
if (file1 == NULL) {
printf("I couldn't open 0.dat for reading.\n");
exit(0);
}
while (!feof(file1)) {
fgets(dat1, n, file1);
m = malloc(sizeof(fract16) * n);
for (i = 0; i < n; i++) {
sscanf(dat1, "%f", &m[i]); //getting error here
}
}
fclose(file1);
printf("%lf\n", m);
return 0;
}
好的,谢谢大家纠正我的错误,但问题仍然没有解决。我能够打印内部的所有值,但在循环之外它只打印数据集的最后一个值,是否有任何精确的解决方案?我用谷歌搜索了几个小时,但还没有成功。 代码如下>
#include <stdlib.h>
#include <stdio.h>
#include <flt2fr.h>
#include<fract_math.h>
#include <math_bf.h>
#include <complex.h>
#include <filter.h>
int main()
{
int n = 1024;
long int dat1[n];
FILE *file1;
fract16 *m;
file1 = fopen("0.dat", "r");
if (file1 == NULL) {
printf("I couldn't open 0.dat for reading.\n");
exit(0);
}
while( !feof(file1))
{
fgets(dat1,n,file1);
sscanf(dat1, "%f", &m);
printf("%f\n",m); //Prints all elements in the 1st column of the array, 0.dat is a nx2 matrix
}
fclose(file1);
}
【问题讨论】:
-
欢迎来到 Stack Overflow!请看Why is “while ( !feof (file) )” always wrong?
-
在使用
dat1之前检查fgets(dat1, n, file1)的返回值 -
取决于我认为的文件中的内容,但这很可能是内存泄漏。你循环了多少次
while循环?只保存指向最后一个malloc的指针。 -
1)
for(i = 0; i < n; i++) { sscanf(dat1, "%f", &m[i]); //getting error here }重复扫描相同的字符串dat1。每次迭代都应该有相同的结果。 2) 如果不发布fract16是什么,我们如何确定它与"%f"(double) 匹配? 3)/getting error here--> 这是什么错误? -
永远不要使用函数:
feor()来控制循环。在这种情况下,建议使用对fgets()的调用,如:while( fgets( dat1, n, file1 )
标签: c embedded signal-processing blackfin