开发者

C/C++ streams and files

开发者 https://www.devze.com 2023-03-31 08:10 出处:网络
I have the following code: int checkCorrectness(int i,char *iStr) { if(atoi(iStr) == i) return 1; return 0;

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

精彩评论

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

关注公众号