Search code examples
cprintffopenfreopen

Is it legal to use freopen and after it fopen ?


Suppose I have a string char* str. I print it to the buffer in the following way:

char buf[MAX_LEN];
freopen("tmp","w",stdout);
printf("%s\n",str);
fflush(stdout);
fp = fopen(tmp,"r");
if (fp == NULL) return;
fgets(buf,MAX_LEN,fp);
fclose(fp);
fclose(stdout);

May this code cause invalid stream buffer handle? Is it legal to use freopen and after it fopen? Based on constrains of my system I can't use fprintf and sprintf.


Solution

  • In theory, it's perfectly legal and works fine. It's even its main use case, according to its man page :

    The freopen() function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it. The original stream (if it exists) is closed. The mode argument is used just as in the fopen() function. The primary use of the freopen() function is to change the file associated with a standard text stream (stderr, stdin, or stdout)

    In practice, your code won't work : there are some mistake mainly between "tmp" and tmp & missing headers. This code will work:

    #include <stdio.h>
    #define MAX_LEN 512
    
    int main() {
      const char* str = "data\n";
      FILE* fp;
      char buf[MAX_LEN];
    
      freopen("tmp","w",stdout);
      printf("%s\n",str);
      fflush(stdout);
      fp = fopen("tmp","r");
      if (fp == NULL) return;
      fgets(buf,MAX_LEN,fp);
      // here, buf gets str's content 
      fclose(fp);
      fclose(stdout);
      return 0;
    }