简体   繁体   中英

EOF going into infinite loop

I am greping and awking some text from a file and writing it to another one.

When I am trying to open and read log_2 to do something, it works fine in case the grep returned some string.

But if grep itself dint return anything , my code is going into an infinite loop. I tried printing the character being read in the loop, it prints a ' ÿ ' infinitely.

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);
}

Can someone explain ?


Just to add in case someone is having similar issue, this code works fine on Intel based Ubuntu systems, but Freescale ones with Ubuntu will cause a problem. So be careful, and always use int to be safe.

EOF is an int not a char .

char cTemp;

should be:

int Temp;

See here for the explanation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM