我目前正在处理下面的 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);
}
最佳答案
您可以在读取文件之前为缓冲区分配内存,在 while 循环之外。然后每次在读入缓冲区之前,只需使用 memset 并将缓冲区设置为所有空字符。
此外,尝试使用 fread 直接读入缓冲区而不是 fgets
关于c - 无法在 while 循环外保留数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40935956/