开发者

C/C++ streams and files

I have the following code:

int checkCorrectness(int i,char *iStr)
{
   if(atoi(iStr) == i)
     return 1;
   return 0;
}
void foo(int i)
{
    printf("inside fo开发者_高级运维o %d\n",i);
}
void print()
{
    char mystring[100];
    freopen("myfile.txt","w+",stdout);
    for(int i =0;i < 100;++i)
    {
      foo(i);
      FILE *f = fopen("myfile.txt","r");
      if (f == NULL) perror ("Error opening file");
      else {
         while ( fgets (mystring , 100 , f) != NULL );
         if(!checkCorrectness(i,mystring);
            break;
         fclose (f);

      }
     }
    fclose(stdout);
}

Is this code save?I mean is it OK to call fopen after freopen was called and its stream was not closed? Thank you


Your code looks safe. You are allowed to open the same file more than once in a process. The file descriptors will not interract.

I'd steer away from reopening stdout like you do. You could do this entire program with a single fopen and avoid the mess you're creating: look up fprintf!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜