簡體   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