【问题标题】:EOF going into infinite loopEOF 进入无限循环
【发布时间】:2012-08-20 07:54:59
【问题描述】:

我正在从一个文件中搜索和唤醒一些文本并将其写入另一个文件。

当我试图打开并读取 log_2 做某事时,如果 grep 返回一些字符串,它可以正常工作。

但如果 grep 本身 dint 返回任何东西 ,我的代码将进入无限循环。我尝试打印循环中正在读取的字符,它会无限打印一个'ÿ'。

system("egrep 'Security = |State = ' log.txt > log_1.txt");
system("awk -F ' Security = | State = { Interface=' '{print $2}' log_1.txt > log_2.txt ");

// The exact strings to be greped and awked are different. Cant write them here.    

FILE *pReadFile;
char cTemp;

pReadFile=fopen ( "log_2.txt" , "r+");

if (pReadFile==NULL )
{
    std::cout << ("Error opening Config file");
    fclose(pReadFile);
    return ;
}

cTemp = fgetc (pReadFile);

if(cTemp == EOF)    
return ; 


while( cTemp != EOF )
{
      // Do Something

      cTemp = fgetc (pReadFile);
}

谁能解释一下?


如果有人遇到类似问题,此代码在基于 Intel 的 Ubuntu 系统上运行良好,但使用 Ubuntu 的飞思卡尔会导致问题。所以要小心,并始终使用 int 以确保安全。

【问题讨论】:

    标签: c++ c linux file


    【解决方案1】:

    EOF 是 int 而不是 char。

    char cTemp;
    

    应该是:

    int Temp;
    

    解释见这里:

    http://c-faq.com/stdio/getcharc.html

    【讨论】:

    • 我正在使用此代码来解析文件并使用正则表达式进行一些匹配。假设 cTemp 仅是 char 类型,我已经完成了与不同字符的匹配。如果我只是将数据类型更改为 int、int 和 char 可以相互转换,它会正常工作吗?
    猜你喜欢
    • 2021-09-07
    • 2014-06-26
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多