Saturday, August 30, 2014

Unix Prog: Standard I/O -- Basic

1. File Orientation

When we create one file using standard I/O library, we say that we have associated the stream with the file.

With ASCII character, a single character occupies one byte. With international character, a single character occupies more than one byte.

Byte-oriented: stream will use ASCII character set
Wide-oriented: stream will use international character set

When a stream is created, it has no orientation, but if we use multibyte I/O function on it(<wchar.h>), it will become wide-oriented. If we use single byte I/O function on it, it will become byte-oriented.

2.fwide

fwide system is used to change one stream's orientation.

definition:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/wchar.h  
 ......  
 /* Select orientation for stream. */  
 extern int fwide (__FILE *__fp, int __mode) __THROW;  
 ......  

fileio.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
 #include<wchar.h>  
 #include<errno.h>  
   
 int main(int argc, char* argv[])  
 {  
  int or;  
   
  errno = 0;  
  FILE *pf = fopen("test.txt", "w+");  
  printf("errno: %d\n", errno);  
  or = fwide(pf, 0);  
  printf("current orientation: %d\n", or);  
  or = fwide(pf, 1);  
  printf("After changing to wide-orientation: %d\n", or);  
   
  // Following call doesn't work, fwide can't change a stream  
  // orientation if it is already oriented. or will still be 1  
  // in following case.  
  or = fwide(pf, -1);  
  printf("After changing to byte-orientation: %d\n", or);  
   
  exit(0);  
 }  

shell:
 ubuntu@ip-172-31-23-227:~$ ./io.out  
 errno: 0  
 current orientation: 0  
 After changing to wide-orientation: 1  
 After changing to byte-orientation: 1  

3. standard input/output/error
When a process is created, there streams are created automatically: standard input, standard output and standard error.These streams are associated with 3 file descriptors: STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO

definition:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/unistd.h  
 ......  
 /* Standard file descriptors. */  
 #define STDIN_FILENO  0    /* Standard input. */  
 #define STDOUT_FILENO  1    /* Standard output. */  
 #define STDERR_FILENO  2    /* Standard error output. */  
 ......  
 ubuntu@ip-172-31-23-227:~$ less /usr/include/stdio.h  
 ......  
 /* Standard streams. */  
 extern struct _IO_FILE *stdin;     /* Standard input stream. */  
 extern struct _IO_FILE *stdout;     /* Standard output stream. */  
 extern struct _IO_FILE *stderr;     /* Standard error output stream. */  
 /* C89/C99 say they're macros. Make them happy. */  
 #define stdin stdin  
 #define stdout stdout  
 #define stderr stderr  
 ......  

No comments:

Post a Comment