1

在用 C 语言读取和写入文件时,我遇到了一些随机故障。通常,算法可以正常工作,但偶尔我会遇到我正在使用的循环停止工作的地方。

我正在使用的文件在读取和写入后显示 [Incomplete last line] 1 line, 2 characters when I VI it,但这是它工作时的样子。我正在跟踪文件中的一个值,并在每次函数执行时用它倒计时。但是,当循环冻结时,我 VI 文件并读取 1 行 3 个字符,没有提到最后一行不完整。在行不完整的情况下不读取文件是有意义的,但这是它实际工作的唯一情况。

我通常可以通过删除文件并让程序重新创建它来解决这个问题,但这意味着在监控应用程序中,所以我需要完全消除故障。我正在使用 fprintf 和 fgets 从文件中读取和写入,据我所知,它们应该正确终止文件,还是我错了?任何帮助将非常感激。谢谢大家。

我在下面附上了我为整个算法编写的代码:

   if loop executes -> 
       {
          /*Set countdown timer for outage, only email after down for 24 hours. */


         if( access( filePath, F_OK ) != -1 ) /* If file does not exist */
         {
           /* Does exist so do nothing */ 
         } 
         else
         {
           if ( ( fileFd = fopen( filePath, "w" ) ) != 0 )
           {
             /* Generates file */
           }

            fclose(fileFd);

           if ( ( fileFd = fopen( filePath, "r+" ) ) != 0 )
           {
             fprintf(fileFd, "%d", bridgeTimer_limit); /* Reset timer to default countdown */
             rewind(fileFd);
             fgets(bridgeOneTimeLeft, 10, fileFd);
             bridgeOneDownCount = atoi(bridgeOneTimeLeft);
           }

         }

         fclose(fileFd);

         if ( ( fileFd = fopen( filePath, "r+" ) ) != 0 )
          { 
            fgets(bridgeOneTimeLeft, 10, fileFd);
            rewind(fileFd);

            bridgeOneDownCount = atoi(bridgeOneTimeLeft);

            if (bridgeOneDownCount > 0) /* Timer still counting down */
            {
              /* Continue timer countdown, decrementing 15 minutes per count */
              bridgeOneDownCount = bridgeOneDownCount - 1;
              fprintf(fileFd, "%d" , bridgeOneDownCount);
              rewind(fileFd);
              pinfo(("bridgeOneDownCount counting down == %d", bridgeOneDownCount));
            }               
            else if (bridgeOneDownCount - 1 <= 0) /* Time reaches 0 */
            {
              sprintf(cmd2,"`which send_alert_email` \'%s\' ", reasonText);
              system(cmd2);
            }
            fclose(fileFd);
          }
       }
   }
   else
   {
     if ( ( fileFd = fopen( filePath, "r+" ) ) != 0 )
     {
       fprintf(fileFd, "%d", bridgeTimer_limit); /* Reset timer to default countdown */
       rewind(fileFd);
       fgets(bridgeOneTimeLeft, 10, fileFd);
       bridgeOneDownCount = atoi(bridgeOneTimeLeft);
     }
     fclose(fileFd);
     return;
   }
4

1 回答 1

1

很难从您的代码中解释错误。请检查可能存在未关闭的某些路径的问题。但是这个程序不需要打开和关闭几次。您可以打开一次,最后关闭。如果您需要中止循环中的其余操作,请continue在“fclose(fileFd)”之后使用关键字。或者最后在循环之后你可以使用

if(fileFd != NULL)
    fclose(fileFd);
于 2013-06-17T15:07:13.743 回答