簡體   English   中英

無法從文件(C)中讀取單個double值

[英]Can't read a single double value from a file (C)

我從文件中讀取單個數據點時遇到麻煩。 它應該能夠讀取兩列數據(例如x和y值),但是我發現我的代碼甚至無法讀取雙精度的單個值。 任何幫助,將不勝感激。

該文件位於D:\\test.txt並且只有一個值1.11111

輸入翼型坐標的文件(文本文件)的位置:D:\\ test.txt有1行。x和y中的數據量分別為1點和1點。 無法閱讀。 *處理返回1 *按任意鍵繼續...

那是我的意見。

/*
    Purpose:
        Create a program that can take in a list of data points that represents an airfoil from some file.
        Then through the use of spline function, spline the data points for interpolation then go on to plotting them.
        With these data points, use the Vortex Panel Method to obtain coefficients of lift, pressure, and tangential velocity.
        Then after these are calculated, plot each with respect to the splined x data points.
*/

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <stdlib.h>
#define LEN 12

int countlines(FILE *fp);

int main (void)
{
    char airfoil[500];
    double *x_data = NULL; 
    double *y_data = NULL;
    FILE *pfile = NULL;
    int line_count = 0;
    double test = 0.0;


    printf("Enter the location of file (text file) of the airfoil coordinates: ");
    scanf("%s", airfoil);

    if(fopen_s(&pfile, airfoil, "r"))
    {
        printf("Error opening the file for reading the data. Program terminated.\n");
        exit(1);
    }

    line_count = countlines(pfile);

    printf("There are %d lines\n", line_count);

    x_data = realloc(x_data, line_count*(sizeof(double)));
    y_data = realloc(y_data, line_count*(sizeof(double)));

    if((!x_data) || (!y_data))
    {
        printf("Memory allocation has failed. Exiting...\n");
        exit(1);
    }

    printf("The amount of data in x and y is %zu points and %zu points.\n", (sizeof(x_data)/sizeof(double)), (sizeof(y_data)/sizeof(double)));

     if(EOF == fscanf_s(pfile, "%lf", &test))
     {
            printf("failed to read.\n");
            exit(1);
    } 
    //for(int i = 0; i < line_count; i++)
    //{
        //fscanf(pfile, " %lf", &x_data[i]);
    //}

    printf("The x-data are %lf!\n", test);
    //for(int i = 0; i < line_count; i++)
    //{
        //printf("%.2lf", x_data[i]);
        //printf("\n");
    //}

    return 0;
}

int countlines(FILE *fp)
{   
    int lines = 0;
    char str[LEN];
    while(!feof(fp))
    {  
        if (fgets(str, LEN, fp) != NULL);
            {
                lines++;
            }
    }

    return lines;
}

countlines只是將文件指針帶到了文件末尾。 在讀取任何內容之前,必須首先將文件倒帶到開頭:

fseek(pfile,0,SEEK_SET);

您可以在countlines()

另請參閱注釋,該注釋會發現更多錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM