stdio in c

 
################################# 
####    IO using <stdio.h>   #### 
################################# 
 
#include <stdio.h>    //  #include <cstdio> in C++. all under std namespace 
// this contains all the below functions, FILE obj, data types like size_t 
 
(ref) 
http://www.tutorialspoint.com/c_standard_library/stdio_h.htm 
 
 
- there are a few ways to categorize IO functions 
 
- read VS write 
- text VS binary 
 
(1) stdin/stdout       // standard input/output 
(2) temp buffer        // some variables 
(3) file stream        // file 
 
for (3), we need fopen(), fclose() and FILE* (a pointer to a FILE obj) 
 
 
see the above URL for the complete list of stdio.h functions. 
below are some basic ones. 
 
 
### 
###  file io 
### 
 
FILE* fopen(const char* filename, const char* mode) 
int fclose(FILE* fptr) 
 
// size_t is unsigned int 
 
 
### 
### text 
### 
 
int printf(const char* format, ...) 
int sprintf(char* str, const char* format, ...) 
int fprintf(FILE* fptr, const char* format, ...) 
 
int scanf(const char* format, ...) 
int sscanf(const char* buff, const char* format, ...) 
int fscanf(FILE* fptr, const char* format, ...) 
 
int getchar() 
int getc(FILE* fptr) 
int fgetc(FILE* fptr) 
char* gets(char* str) 
char* fgets(char* str, FILE* fptr) 
 
int putchar(int char) 
int putc(int char, FILE* fptr) 
int fputc(int char, FILE* fptr) 
int puts(const char* str) 
int fputs(const char* str, FILE* fptr) 
 
 
 
### 
### binary 
### 
 
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) 
int fclose(FILE* fptr) 
 
 
NOTE:  since text\binary are only data representation difference, we can use fgets(), fputs() for binary data processing as well. 
 
 
 
### 
### control 
### 
 
int fseek(FILE* fp, long int offset, int pos) 
long int ftell(FILE* tp) 
void rewind(FILE* fp) 
 
 
 
 
######################################### 
####    function usage & examples    #### 
######################################### 
 
 
int printf(const char* format, ...) 
   // print to stdout 
   // returns the number of characters written if success 
   // returns a negative num if fail 
 
int sprintf(char* str, const char* format, ...) 
   // print to str aka buffer 
   // returns the number of char if success, excluding the terminator null 
   // returns a negative num if fail 
 
int fprintf(FILE* fptr, const char* format, ...) 
   // print to fptr aka stream which can be stdout 
   // returns the number of characters written if success 
   // returns a negative num if fail 
 
 
 
int scanf(const char* format, ...) 
   // takes input from stdin to each variables 
   // returns the number of characters written if success 
   // returns a negative num if fail 
 
 
------- example --------- 
 
char str[6]; 
int num; 
scanf("%s %d", str, &num);   // type "hello 1234" in stdin 
                             // str = "hello" 
                             // num = 1234 
------------------------- 
 
 
 
int sscanf(const char* buff, const char* format, ...) 
   // reads from buff and maps the contents to each variable 
   // returns the num of variables filled. EOF if failed. 
 
-------- example ---------- 
 
char* str0 = "this is 2014"; 
int num; 
char* str1[5]; 
char* str2[3]; 
 
sscanf( buff, "%s %s %d", str1, str2, &num ); 
 
--------------------------- 
 
 
 
int fscanf(FILE* fptr, const char* format, ...) 
   // takes input from fptr to each variables 
   // returns the number of input items matched and assigned. could be 0. 
 
---------- example --------  // testfile contains "this is 2014" 
 
char str1[5]; 
char str2[5]; 
int num; 
FILE* fptr = fopen("testfile","r"); 
fscanf(fptr, "%s %s %d", str1, str2, &num); 
fclose(fptr); 
 
-------------------------- 
 
 
 
 
int getchar() 
   // gets a char from stdin 
   // same as getc(stdin) 
   // returns the char in int format if success 
   // returns EOF if fail 
 
int getc(FILE* fptr) 
   // gets a char from ftpr 
   // returns the char in int format if success 
   // returns EOF if fail 
 
int fgetc(FILE* fptr) 
   // same as getc() 
   // only implementation details differ. 
   // fgetc() is preferred cos getc() may be implemented as a macro 
 
char* gets(char* str) 
   // reads input from stdin and maps to str 
   // terminates when a newline or EOF is reached 
 
char* fgets(char* str, FILE* fptr) 
   // reads input from fptr, and writes to str till newline or EOF 
   // returns the str if success, NULL if error 
 
 
int putchar(int char) 
   // writes a char to stdout 
   // returns what it wrote or EOF if failed 
 
int putc(int char, FILE* fptr) 
   // writs a char into ftpr 
   // returns what it wrote or EOF if failed 
 
int fputc(int char, FILE* fptr) 
   // same as putc() 
   // only implementation details differ. 
   // fputc() is preferred as putc() may be implemented as a macro 
 
int puts(const char* str) 
   // writes str to stdout until NULL. NULL itself is not printed. 
   // returns non-negative val if success,  EOF if failed 
 
int fputs(const char* str, FILE* fptr) 
   // writes str to fptr until NULL. NULL itself is not written. 
   // returns non-negative val if success,  EOF if failed 
 
 
 
 
------------------------ 
 
#include <stdio.h> 
 
int main()    // you can omit "int" then compiler will deduce 
{             // void main() is deprecated 
 
   printf("hello world"); 
   rewind(stdin);        // flush the stdin 
   char c; 
   c = getchar();            // get one char from stdin 
   printf("%c\n",c); 
 
   char str[] = "hello"; 
   int num = 777; 
   float foo = 123.4567; 
   printf("str:%s num:%d foo:%f", str, num, foo); 
   printf("%4s %5d %3.2f", str, num, foo); 
   printf("%05d", str, num, foo); 
 
   fprintf(stdout, "num:%d", num); 
 
   scanf("%d", &num);   // from stdin 
                        // %d regulates the input data type, 
                        // so if you type "hello", it will be ignored. 
 
   char str[6]; 
   gets(str);      // type in "hello" 
   printf(%s,str); 
 
   int cc; 
   scanf(%cc,&cc);  //  cc = getchar() 
   printf("%cc",cc); 
 
   return 0;  // zero says successful exit for unix os 

------------------------ 
 
 
 
 
int fseek(FILE* fp, long int offset, int pos) 
     // random access to fp[offset + pos]      // essentially it's byte count 
     // for pos, we have constant defined 
     // SEEK_SET : beginning of file 
     // SEEK_CUR : current pos of the file ptr 
     // SEEK_END : end of file 
 
long int ftell(FILE* fp) 
     // returns the current pos of file ptr. 
 
void rewind(FILE* fp) 
     // sets the pos of the file ptr to the beginning of the file. same as fseek(fp, 0, SEEK_SET); 
 
 
-------------  example  ------------- // fseek(), ftell(), rewind() 
 
#include <stdio.h> 
 
int main() 

   FILE* fp = fopen("test.txt","w+"); 
 
   printf("%d",ftell(fp));       // 0 
   fputs("I am foo",fp); 
   printf("%d",ftell(fp));       // 8 
 
   // pos : 0 1 2 3 4 5 6 7 
   // char: I   a m   f o o 
 
   fseek(fp, 5, SEEK_SET);       // goto the 6th byte 
   fputs("bar",fp);              // this will convert "I am foo" to "I am bar" 
   long int size = ftell(fp);    // size = 8 
 
   rewind(fp);                   // same as  fseek(fp, 0, SEEK_SET); 
   printf("%d",ftell(fp));       // 0 
 
   int i; 
   for(i=0 ; i<size ; i++) 
      printf("%c",fgetc(fp));    // "I am bar" 
 
   fseek(fp, 0, SEEK_END); 
   printf("%d",ftell(fp));       // 8 
 
   fclose(fp); 

 
--------------------------------------// 
 
 
 
############################ 
###   format specifier   ### 
############################ 
 
c|%  // character 
s    // string 
d|i  // signed decimal integer 
u    // unsigned decimal integer 
x    // unsigned hex interger 
p    // pointer addr 
f    // decimal floating point 
o    // signed octal 
 
 
-------------------------- 
int num = 1984; 
printf("%s %s %s %d", "The", "book", "is", num); 
 
printf("foo %6.2f", 123.4567);  // foo 123.46 
printf("foo %6.2f", 3.4);       // foo    3.4 
-------------------------- 
 
==>  %6.2f means pad to use 6 chars (including a dot), and round to 2nd decimal place. 
     alternatively you can do %.3f which means no padding, just round to the 3rd decimal place. 
     (this convention is true in other languages. e.g. Perl, C++) 
 
 
############################# 
###   control character   ### 
############################# 
 
\a       # ring a bell 
\b       # backspace 
\f       # new page 
\n       # new line 
\0       # null 
\'       # single quote 
\"       # double quote 
\\       # back slash 
\t       # tab (horizontal) 
\v       # tab (vertical) 
\r       # 
 
 
 
###################### 
####   file io    #### 
###################### 
 
text or binary 
 
 
FILE* fopen(const char* filename, const char* mode) 
// returns NULL if fail 
 
int fclose(FILE* fptr) 
// zero if success, EOF ( usually = -1 ) if fail. 
 
// mode 
"r"       // read only 
"w"       // write only 
"a"       // append(additional write) only 
"r+"      // open a file for both read/write 
"w+"      // create a new empty file for both read/write 
"a+"      // open a file for both read/append 
"rb"      // read only (binary mode) 
"wb"      // write only (binary mode) 
 
 
(ref) 
http://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm 
 
 
 
(1) text 
 
---------------------- 
#include <stdio.h> 
#include <stdlib.h> 
 
int main() 

   char inputstr[15]; 
   gets(inputstr);                       // type in the input file name less than 15 chars 
   FILE *fptr = fopen(inputstr, "r");    // FILE is a data type 
                                         // fopen() returns a ptr to FILE 
                                         // absolute path can be used also 
 
 
   char c; 
   char str[5]; 
 
   if(!fptr)   // if null 
   { 
      printf("fopen error"); 
      exit(1); 
   } 
 
   while( (c = fgetc(fptr)) != EOF)   // c can be "\n" 
       printf("%c",c); 
 
   //  while( fgets(str, 4, fptr) )   // reads until "\n" or EOF 
   //     print("%s" ,str); 
 
   fclose(fptr); 
 
   return 0; 

 
 
 
 
 
 
 
-------------------------------------------------- 
 
 
(2) binary 
 
 
size_t fread(void *ptr, size_t unit_of_read, size_t num_of_read, FILE *fptr) 
 
   // returns the number of times it read. so 0 means EOF. 
   // '\n' is counted as one byte 
   // in the above case, fread() will return 1 to 9 until EOF that is 0 
 
fread( arg1, arg2, arg3, arg4) 
 
arg1 = buffer for storing the input data 
arg2 = unit of read ( 1 means 1 byte) 
arg3 = number of read 
arg4 = file pointer 
 
fgets(), fputs() can also be used for binary file io. 
 
int fclose(FILE* fptr) 
   // closes the fptr file stream 
   // returns zero if success, EOF if failed. 
 
 
 
---------------- example ------------------------- 
 
#include <stdio.h>      // for fread(), fwrite() 
#include <stdlib.h> 
 
int main() 

   int input; 
   char buff[10]; 
   FILE* fptr = fopen("testfile", "rb"); 
   FILE* wfptr= fopen("outfile", "wb") 
 
   if(!fptr || !wfptr) 
   { 
      printf("fopen error"); 
      exit(1); 
   } 
 
   // reads 9 bytes and put them into buff[0] to buff[8], 
   // then put null into buff[9] so we can print it out with a proper terminator 
   // if less than 9 bytes remaining before EOF, then read that n <= 9 bytes 
   while ( (input = fread(buff, sizeof(char), 9, fptr)) != 0 ) 
   { 
      buff[input] = '\0'; 
      printf("%s",buff); 
      fwrite(buff, sizeof(char), input, wfptr); 
   } 
 
   fclose(fptr); 
   fclose(wfptr); 
   return 0; 

 
----------------------------------- 
 

  1. 2014-06-19 16:01:35 |
  2. Category : unix
  3. Page View:

Google Ads