C - 从文件中读取大量数字

时间:2013-03-19 09:43:03

标签: c file floating-point

我有一个包含大数字的文件,例如-7.47004e-16,我正在尝试使用

将其读入浮点数组
fscanf(rhs, "%f", &numbers[i]);" 

这是一个while循环。但是当我们有一个如上所述的数字时,这不起作用。

由于数量如此之大,这不起作用吗?或者这不是数字格式中“e”的原因吗?

你能否推荐一些正确的方法?

感谢。

注意:Numbers是一个float数组,rhs是文件名。该文件每行有一个数字,有些数字与上面的格式相同,有些数字要小得多,例如-1.88493

以下是代码:

int main( int argc, char *argv[])
{
    FILE *rhs, *output;
    int niter, n, n1;
    // counters
    int i = 0, j = 0, k, m, p;

    rhs = fopen(argv[1], "r");
    // ab+ opens file for writting and creates the file if need be
    output = fopen(argv[2], "ab+");
    niter = atoi(argv[3]);

    // check if files open up or not, if not exit.
    if((rhs == NULL) || (output == NULL))
    {
        printf("Error Opening files.\n");
        exit(1);
    }

    // read in N
    fscanf(rhs, "%d", &n);

    // initialize n1
    n1 = n + 1;

    // generate array to hold values from rhs file
    long double *numbers = (long double *)malloc(sizeof(long double) * ((n1)*(n1)));
    long double *y = (long double *)malloc(sizeof(long double) * ((n1)*(n1)));
    long double *f = (long double *)malloc(sizeof(long double) * ((n1)*(n1)));
    long double *yp = (long double *)malloc(sizeof(long double) * ((n1)*(n1)));

    // get numbers and store into array
    for(i = 0; i <= n; i++)
    {
        for(j = 0; j <= n; j++)
        {
            fscanf(rhs, "%Lf", &numbers[i]);
            printf("i = %d, number = %Lf\n", i, numbers[i]);
        }
    }

    for(k = 0; k < niter; k++)
    {
        smooth(n, y, yp, f);
    }

    fclose(rhs);
    free(numbers);
    free(y);
    free(f);
    free(yp);

    return 0;

}

3 个答案:

答案 0 :(得分:5)

SSCCE(Short, Self-Contained, Correct Example

#include <stdio.h>

int main(void)
{
    FILE *rhs = stdin;
    int i = 0;
    float numbers[2];

    if (fscanf(rhs, "%f", &numbers[i]) != 1)
        printf("Failed to convert anything\n");
    else
        printf("Got: %13.6e\n", numbers[i]);
    return 0;
}

示例运行:

$ ./flt
-7.47004e-16
Got: -7.470040e-16
$

请注意,代码会检查转换是否成功;您应该始终这样做,并且正确的测试如下所示 - 您是否获得了正确的成功转换次数。你可以在不进入EOF的情况下进行转换失败,因此针对EOF的测试是不正确的。

答案 1 :(得分:1)

这个特定的数字对于IEEE754单精度浮点来说并不算太大,所以应该没问题。

我自己只使用double来增加范围和精度,但这是个人偏好。

我想澄清一件事:你说rhs是一个文件名称。我希望它真的是fopen返回的文件句柄,否则这将带来一个大问题: - )

此外,我认为你的意思是文件每个行有一个数字而不是每个文件。

作为示例,请参阅以下脚本,该脚本显示输入文件,使用fscanf的C程序和输出,以查看此方法应该正常工作:

pax> cat qq.in
    -7.47004e-16
    3.14159
    2.718281828459
    42

pax> cat qq.c
    #include <stdio.h>
    #include <math.h>

    int main (void) {
        float f;
        FILE *fin = fopen ("qq.in", "r");
        while (fscanf (fin, "%f", &f) == 1)
            printf ("    %f %e\n", f, f);
        fclose (fin);
        return 0;
    }

pax> ./qq
    -0.000000 -7.470040e-16
    3.141590 3.141590e+00
    2.718282 2.718282e+00
    42.000000 4.200000e+01

答案 2 :(得分:0)

我不认为这是浮动的大小限制,因为它可能代表2e−126,大约1.18 *10e−38。也许你在打印时没有指出浮动的精度?

尝试将其打印出来:

printf("%.30f\n", f);