Saturday, August 30, 2014

Unix Prog: Standard I/O -- Open Stream(2)

1. freopen

freopen will open the existing file and associate it to one existing stream.
fileio.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
   
 int main(int argc, char* argv[])  
 {  
  FILE *fp;  
   
  // Open "test.txt" for reading and writing, and associate the  
  // stdout stream to this file. Firstly, it will clear the stream  
  // (standard output), then clear stream orientation if there is,  
  // lastly associate the "test.txt" to existing stream stdout.  
  if((fp = freopen("test.txt", "w+", stdout)) == NULL) {  
   printf("freopen error!\n");  
   exit(1);  
  }  
   
  // output the string to standard output, which refers to test.txt now  
  printf("Hello world!\n");  
   
  // output the string to file descriptor fp.  
  fputs("Amazing world!\n", fp);  
   
  exit(0);  
 }  

shell:
 ubuntu@ip-172-31-23-227:~$ ./io.out  
 ubuntu@ip-172-31-23-227:~$ cat test.txt  
 Hello world!  
 Amazing world!  

2. fdopen

fdopen will associate a new standard I/O stream to one existing file descriptor.

fileio.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
 #include<fcntl.h>  
   
 int main(int argc, char* argv[])  
 {  
  int fd;  
  FILE *fp;  
   
  // Open the file for "READ ONLY"  
  if((fd = open("test.txt", O_RDONLY)) == -1) {  
   printf("open error!\n");  
   exit(1);  
  }  
   
  // Associate a standard I/O stream to above file descriptor  
  // but the I/O stream is for writing only, which is in conflict  
  // with file descriptor's mode -> "O_RDONLY"  
  // This conflict will make fdopen return NULL  
  if((fp = fdopen(fd, "w")) == NULL) {  
   printf("fdopen w error!\n");  
  }  
   
  // This one is ok, since the mode of fdopen is consistent with  
  // file descriptor's mode  
  if((fp = fdopen(fd, "r")) == NULL) {  
   printf("fdopen r error!\n");  
  }  
   
  // fclose is used close the file stream
  fclose(fp);

  exit(0);  
 }  

shell:
 ubuntu@ip-172-31-23-227:~$ ./io.out  
 fdopen w error!  

Note:
1) "w", "w+" can't truncate the file in this system call, since the file already existed.
2) "w", "w+", "a", "a+" can't create new files since file already exists.
3) For stream opened for reading and writing, output can not be directly followed by the input without an intervening fflush, fseek, fsetpos, or rewind. Input cannot be directly followed by output without an intervening fseek, fsetpos, or rewind, or and input operation that encounters the end of file.

No comments:

Post a Comment