【发布时间】:2016-03-07 18:20:14
【问题描述】:
所以我在存储 .dat 文件中的一些数字时遇到了一些困难。文件如下:
1
2
7
10
9
4
0
5
6
8
3
我必须尝试检索此信息的代码是:
#include <stdio.h>
#include <stdlib.h>
#define N 11
int main(int argc, char** argv) {
//Declare variables: number of elements, counter, array, & valuesto
//print
int i;
double a[N], num, temp;
FILE* dat;
//Print space for program cleanliness
printf("\n");
//Open file
dat = fopen("zero.dat", "r");
//Initialize i
i=0;
//Read in infromation from file
while(!feof(dat) && i < N){
printf("This is loop number %d\n", i);
num = fscanf(dat,"%lf", &temp);
printf("Temp variable is stored as: %f\n", temp);
printf("Number of characters read in: %d\n\n", num);
a[i] = temp;
i++;
}
fclose(dat);
for(int j=0;j<i;j++){
printf("%f\n", a[j]);
}
//Exit program
exit(EXIT_SUCCESS);
}
/**************************************************************************/
输出是:
This is loop number 0
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072
This is loop number 1
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072
This is loop number 2
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072
This is loop number 3
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072
This is loop number 4
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072
This is loop number 5
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072
This is loop number 6
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072
This is loop number 7
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072
This is loop number 8
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072
This is loop number 9
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072
This is loop number 10
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
另外,需要注意的是我使用的是 NetBeans IDE 8.0.2; zero.dat 文件与源文件位于同一项目文件夹中。
【问题讨论】:
-
您的
num是双精度数,但您将其打印为整数。fscanf的返回值是一个int,但它不返回扫描的字符数,而是格式转换的次数或特殊值EOF表示已经到达文件末尾。 -
总是检查
fopen();的结果 -
如果我将
num更改为int,您的示例对我有用。您应该检查文件是否可以像 Peter Miehle 指出的那样打开。可能导致转换错误的另一件事是文件编码。例如,如果您的文件有 BOM(字节顺序标记),fscan会尝试从中转换双精度,但失败了。因为失败的转换会将文件指针返回到它的旧位置,所以所有的转换都会失败。尝试将文件保存为没有 BOM 的纯 ASCII 或 UTF-8。 -
您可以对文件进行十六进制转储,以查看文件开头是否有任何“奇怪”字符。如果是这样,请在文本编辑器中更改编码并再次保存文件。