This blog is under construction

Thursday 5 April 2012

freopen example in C

Header file:
     stdio.h

Synopsis:
     FILE *freopen(const char *path, const char *mode, FILE *stream);

Description:
     Opens the given file in the specified mode and associates the stream with it.  Returns stream on success, or NULL on failure.


freopen stdin example:


  #include<stdio.h>
  #include<string.h>
  int main() {
        FILE *fp;
        char str[100];

        fp = freopen("file.txt", "r", stdin);
        while (1) {
                fgets(str, sizeof(str), stdin);
                str[strlen(str) - 1] = '\0';
                if (strncmp(str, "quit", 4) == 0)
                        break;
                else
                        puts(str);
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat file.txt 
  hello world
  hello world
  hello world
  quit

  jp@jp-VirtualBox:~/$ ./a.out
  hello world
  hello world
  hello world




freopen stdout example:


  #include<stdio.h>
  #include<string.h>
  int main() {
        FILE *fp;
        char str[100];
        fp = freopen("file.txt", "w", stdout);
        printf("Enter your input:\n");
        fgets(str, sizeof(str), stdin);
        printf("%s", str);
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ls
  a.out  freopen.c  freopen_err.c  freopen_out.c
  jp@jp-VirtualBox:~/$ ./a.out
  hello world
  jp@jp-VirtualBox:~/$ ls
  a.out  freopen.c  freopen_err.c  freopen_out.c  file.txt
  jp@jp-VirtualBox:~/cpgms/exp$ cat file.txt
  Enter your input:
  hello world




freopen stderr example:


  #include<stdio.h>
  #include<string.h>
  int main() {
        FILE *fp;
        fp = freopen("file.txt", "w", stderr);
        fputs("hello world\n", stderr);
        fclose(fp);
        return 0;
  }


  Output:
  jp@jp-VirtualBox:~/cpgms/exp$ ls
  a.out  freopen.c  freopen_err.c  freopen_out.c
  jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
  jp@jp-VirtualBox:~/cpgms/exp$ cat file.txt
  hello world


No comments:

Post a Comment