簡體   English   中英

如何使用 C 從 .txt 文件中讀取最后 3 個變量值

[英]How to read last 3 variable values from .txt file using C

我用 C 編程的經驗有限,但由於軟件限制不得不使用這種語言。 我正在嘗試為 CFD 軟件編寫用戶自定義。

軟件在計算過程中寫入一個輸出文件,我想監視變量“PERCENT FILLED”並在值穩定時終止模擬。 我可以終止代碼,我遇到的問題是使用 C 讀取 PERCENT FILLED 的值,我可以在 python 或 shell 腳本中輕松完成此操作,但我真的很喜歡 C。

可能有一種更優雅的方法來做到這一點,我很高興學習,但我不是一個有經驗的程序員,所以我可能會迷失在復雜的解決方案中。

我試圖通過將任務分解為更小的子任務來做到這一點。 代碼的效率並不重要,因為此函數不必頻繁運行,而且要讀取的文件不是很大。 我相信有更快更優雅的方法來做到這一點! 使用來自網絡的其他代碼並修改它們,我想出了以下內容。

我嘗試執行以下子任務:A)剝離包含“PERCENT FILLED”的所有行並將它們寫入文件(PERCENT FILLED.txt)B)讀取此文件中的行數,然后將最后 3 行讀入單獨的變量。 C) 然后我需要重新格式化這些變量。 例如,將 3 個變量從“PERCENT FILLED = 6.72902E+00”形式的字符串更改為浮點數,例如 6.72902。

我已經完成了 A),在 B) 中有錯誤,並且不知道從哪里開始 C)。

B) 中的錯誤 - 當我運行代碼時,它會在 while 循環中正確地為 line1、line2 和 line3 分配值,但是一旦在 while 循環之外,所有值都會更改為 line1 的值。 這我不明白。 誰能幫我理解和解決這個問題?

示例代碼輸出:

line3: PERCENT FILLED =   6.31275E+00
line2: PERCENT FILLED =   6.50146E+00
line1: PERCENT FILLED =   6.72902E+00
****************** 
out line1: PERCENT FILLED =   6.72902E+00
out line2: PERCENT FILLED =   6.72902E+00
out line3: PERCENT FILLED =   6.72902E+00

C部分) - 我不知道從哪里開始。 看起來有足夠的內聯信息可以使用 atof() 將字符串轉換為浮點數。 但是,我首先需要從字符串的開頭刪除 PERCENT FILLED = ,然后轉換工程編號格式(有些值為 1.00E+02 所以簡單地去除最后 4 個字符 - E+00 - 將不起作用)。 這我不知道該怎么做。 任何幫助,將不勝感激。

示例輸入文件(通過刪除 PERCENT FILLED 值之間的 may 行來簡化):

  Step = 171 Iteration = 0 Time step = 0.014849 Time = 4.834002
  Iter Variable Solver Loops          Delta      Solve CPU       Form CPU
     0        F  EXPLC     4   1.0000000E+00       0.007999       0.000000
 FRACTION SOLID = 0.000000e+00 %
 PERCENT FILLED =   5.46882E+00
  Step = 172 Iteration = 0 Time step = 0.029698 Time = 4.863700
  Iter Variable Solver Loops          Delta      Solve CPU       Form CPU
     0        F  EXPLC    11   1.0000000E+00       0.018997       0.000000
 FRACTION SOLID = 0.000000e+00 %
 PERCENT FILLED =   5.70902E+00
  Step = 173 Iteration = 0 Time step = 0.029698 Time = 4.893398
  Time step reduced by COURANT limit in free_surface, c_lim = 2.032750e-02
  Iter Variable Solver Loops          Delta      Solve CPU       Form CPU
     0        F  EXPLC     6   1.0000000E+00       0.010998       0.000000
 FRACTION SOLID = 0.000000e+00 %
 PERCENT FILLED =   5.89665E+00
  Step = 174 Iteration = 0 Time step = 0.020328 Time = 4.904356
  Iter Variable Solver Loops          Delta      Solve CPU       Form CPU
     0        F  EXPLC     7   1.0000000E+00       0.011997       0.000000
 FRACTION SOLID = 0.000000e+00 %
 PERCENT FILLED =   6.08026E+00
  Step = 175 Iteration = 0 Time step = 0.040655 Time = 4.945011
  Time step reduced by COURANT limit in free_surface, c_lim = 2.547617e-02
  Iter Variable Solver Loops          Delta      Solve CPU       Form CPU
     0        F  EXPLC     9   1.0000000E+00       0.016998       0.000000
 FRACTION SOLID = 0.000000e+00 %
 PERCENT FILLED =   6.31275E+00
  Step = 176 Iteration = 0 Time step = 0.025476 Time = 4.955307
  Time step reduced by COURANT limit in free_surface, c_lim = 1.997734e-02
  Iter Variable Solver Loops          Delta      Solve CPU       Form CPU
     0        F  EXPLC     9   1.0000000E+00       0.016994       0.000000
 FRACTION SOLID = 0.000000e+00 %
 PERCENT FILLED =   6.50146E+00
  Step = 177 Iteration = 0 Time step = 0.039955 Time = 4.989764
  Time step reduced by COURANT limit in free_surface, c_lim = 2.547537e-02
  Iter Variable Solver Loops          Delta      Solve CPU       Form CPU
     0        F  EXPLC    13   1.0000000E+00       0.024994       0.000000
 FRACTION SOLID = 0.000000e+00 %
 PERCENT FILLED =   6.72902E+00

我目前的代碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char line[1000];
    char *pch;
    char c[] = "PERCENT FILLED =";
    char buff[1000];


/* Create a list of PERCENT FILLED values and write to file - copy every line containing PERCENT FILLED from p.out file*/
    FILE *fp = fopen("inputFILE.txt", "r");
    FILE *op = fopen("PERCENT_FILLED.txt", "w");

    if(fp == NULL || op == NULL)
       {
          fprintf(stderr, "Error opening file.");
          exit(1);
       }
    else 
       {
         while (fgets(line, sizeof(line), fp) != 0)
           {
              if((pch = strstr (line, c))!= 0)
              fprintf(op, "%s", line);
           }
       }

   fclose(fp);
   fclose(op);


/* Get the total number of lines in the file PERCENT_FILLED.txt   */

   FILE* myfile = fopen("PERCENT_FILLED.txt", "r");
   int ch, number_of_lines = 0;
   int line_num = 0;
   int count = 0;
   char readline[256];                                /* or other suitable maximum line size */
   char* line1;
   char* line2;
   char* line3;

    do 
    {
        ch = fgetc(myfile);
        if(ch == '\n')
            number_of_lines++;
    } while (ch != EOF);

    // last line doesn't end with a new line!
    // but there has to be a line at least before the last line
    if(ch != '\n' && number_of_lines != 0) 
        number_of_lines++;

    fclose(myfile);




/* Get the last 3 PERCENT_FILLED values from the PERCENT_FILLED.txt   */


    FILE* infile = fopen("PERCENT_FILLED.txt", "r");

    if ( infile != NULL )
    {   
        while (fgets(readline, sizeof line, infile) != NULL) /* read a line */
        {   
            if (count == (number_of_lines-4))
            {   
               line3 = readline;
               count++;
               printf("\nline3:%s", line3);
            }   
            else if (count == (number_of_lines-3))
            {  
               line2 = readline;
               count++;
               printf("line2:%s", line2);
            }
            else if (count == (number_of_lines-2))
            {
               line1 = readline;
               count++;
               printf("line1:%s", line1);
            }
            else
            {   
                count++;
                printf("readline:%s count:%d\n", readline, count);
            }   
        }   
        fclose(infile);
    }   
    printf("******************\n");
    printf("out line1:%s", line1);
    printf("out line2:%s", line2);
    printf("out line3:%s\n\n", line3);


/* strip "PERCENT FILLED = " from the string and turn the string into a float  */
/* Do this for line1, line2, line3 */
/* Example string is "  PERCENT FILLED =   6.72902E+00" need to turn this in to a float variable of value 6.72902 */

    return 0;

}

感謝您的幫助,我現在的代碼如下所示。 我確信有一種更優雅的方法可以做到這一點,但為了完整起見,我將提供我的最終代碼,以防它可以幫助某人。

    #include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char line[1000];
    char *pch;
    char c[] = "PERCENT FILLED =";
    char buff[1000];


/* Create a list of PERCENT FILLED values and write to file - copy every line containing PERCENT FILLED from p.out file*/
    FILE *fp = fopen("inputFILE.txt", "r");
    FILE *op = fopen("PERCENT_FILLED.txt", "w");

    if(fp == NULL || op == NULL)
       {
          fprintf(stderr, "Error opening file.");
          exit(1);
       }
    else 
       {
         while (fgets(line, sizeof(line), fp) != 0)
           {
              if((pch = strstr (line, c))!= 0)
              fprintf(op, "%s", line);
           }
       }

   fclose(fp);
   fclose(op);


/* Get the total number of lines in the file PERCENT_FILLED.txt   */

   FILE* myfile = fopen("PERCENT_FILLED.txt", "r");
   int ch, number_of_lines = 0;
   int line_num = 0;
   int count = 0;
   char readline[256];                                /* or other suitable maximum line size */
   char line1[256];
   char line2[256];
   char line3[256];

    do 
    {
        ch = fgetc(myfile);
        if(ch == '\n')
            number_of_lines++;
    } while (ch != EOF);

    // last line doesn't end with a new line!
    // but there has to be a line at least before the last line
    if(ch != '\n' && number_of_lines != 0) 
        number_of_lines++;

    fclose(myfile);




/* Get the last 3 PERCENT_FILLED values from the PERCENT_FILLED.txt   */


    FILE* infile = fopen("PERCENT_FILLED.txt", "r");

    if ( infile != NULL )
    {   
        while (fgets(readline, sizeof line, infile) != NULL) /* read a line */
        {   
            if (count == (number_of_lines-4))
            {   
               strcpy ( line3, readline);
               count++;
            }   
            else if (count == (number_of_lines-3))
            {  
               strcpy ( line2, readline);
               count++;
            }
            else if (count == (number_of_lines-2))
            {
               strcpy ( line1, readline);
               count++;
            }
            else
            {   
                count++;
            }   
        }   
        fclose(infile);
    }      

/* strip "PERCENT FILLED = " from the string and turn the string into a float  */
/* Do this for line1, line2, line3 */
/* Example string is "  PERCENT FILLED =   6.72902E+00" need to turn this in to a float varaible of value 6.72902 */

    char per1[7], fil1[6], eq1[1];
    char per2[7], fil2[6], eq2[1];
    char per3[7], fil3[6], eq3[1];
    float value1, value2, value3;

    sscanf (line1, "%s %s %s %E", per1, fil1, eq1, &value1 );
    sscanf (line2, "%s %s %s %E", per2, fil2, eq2, &value2 );
    sscanf (line3, "%s %s %s %E", per3, fil3, eq3, &value3 );

    printf("Value1: %f\n", value1 );
    printf("Value2: %f\n", value2 );    
    printf("Value3: %f\n", value3 );


    return 0;

    }

暫無
暫無

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

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