繁体   English   中英

C-从文件中大量读取

[英]C - Read in a large number from file

我有一个文件较大,例如-7.47004e-16 ,我正在尝试使用以下命令将其读入一个浮点数组

fscanf(rhs, "%f", &numbers[i]);" 

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

由于数量太大,这不起作用吗? 还是这不是数字格式中“ e”的工作原因?

您能推荐一些正确执行此操作的方法吗?

谢谢。

注意:Numbers是一个浮点数组,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;

}

SSCCE( 简短,独立,正确的示例

#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的测试不正确。

对于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

我不认为这是float的大小限制,因为它最多可以表示2e−126 ,大约为1.18 *10e−38 也许您在打印时没有指出浮点的精度?

尝试像这样打印出来:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM