EOF进入无限循环

时间:2012-08-20 07:54:59

标签: c++ c linux file

我正在为一个文件中的一些文本进行greping和awking并将其写入另一个文件。

当我尝试打开并读取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来保证安全。

1 个答案:

答案 0 :(得分:4)

EOFint而不是char

char cTemp;

应该是:

int Temp;

请参阅此处获取解释:

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

相关问题