Programming C : stdio.h Example 3

 fclose: Closes the file and flushes its buffer

//Declaration :  int fclose(FILE *stream);
//Return value:  If successful, zero is returned, or EOF is returned.


  #include <stdio.h>
  #include <stdlib.h>

  int main(void)
  {
    FILE *fp;

    if((fp=fopen("test", "rb"))==NULL) {
      printf("Cannot open file.\n");
      exit(1);
    }

    if(fclose(fp))
        printf("File close error.\n");

    return 0;
  }

ferror: check for a file error

//Declaration:  int ferror(FILE *stream); 
//Return:       0: no error has occurred.   
                Nonzero: an error has occurred.  

  #include <stdio.h>
  #include <stdlib.h>

  int main(void){
     FILE *fp;

     if((fp=fopen("test", "rb"))==NULL) {
        printf("Cannot open file.\n");
        exit(1);
     }

     putc('C', fp);
     if(ferror(fp)) {
       printf("File Error\n");
       exit(1);
     }
    
     fclose(fp);
     return 0;
  }

fgetc: gets a character from the stream and increments the file position pointer

    

//Header:        #include <stdio.h>  
//Declaration:   int fgetc(FILE *stream); 
//Return:        EOF: if the end of the file is reached. 


  #include <stdio.h>
  #include <stdlib.h>

  int main(int argc, char *argv[])
  {
    FILE *fp;
    char ch;

    if((fp=fopen("test","r"))==NULL) {
      printf("Cannot open file.\n");
      exit(1);
    }

    while((ch=fgetc(fp)) != EOF) {
      printf("%c", ch);
    }
    fclose(fp);

    return 0;
  }

fgets: reads up to num-1 characters from stream and stores them in *str

    

//Header:       #include <stdio.h>  
//Declaration:  char *fgets(char *str, int num, FILE *stream); 
//Return:       returns str on success or a NULL pointer on failure 


  

  #include <stdio.h>
  #include <stdlib.h>

  int main(int argc, char *argv[])
  {
    FILE *fp;
    char str[128];

    if((fp=fopen("test", "r"))==NULL) {
      printf("Cannot open file.\n");
      exit(1);
    }

    while(!feof(fp)) {
      if(fgets(str, 126, fp)) printf("%s", str);
    }

    fclose(fp);

    return 0;
  }

fprintf: outputs the values to the stream

    

//Header:       #include <stdio.h>  
//Declaration:  int fprintf(FILE *stream, const char *format, ...); 
//Return:       returns the number of characters printed on 
                success or a negative number on failure. 




  
  #include <stdio.h>
  #include <stdlib.h>

  int main(void)
  {
    FILE *fp;

    if((fp=fopen("test", "wb"))==NULL) {
      printf("Cannot open file.\n");
      exit(1);
    }
    //The format control string are identical to those in printf();
    fprintf(fp, "this is a test %d %f", 10, 20.01);
    fclose(fp);

    return 0;
  }

fputs: writes a string to the stream(The string's null terminator is not written)

   
//Header file:     #include <stdio.h>  
//Declaration:     int fputs(const char *str, FILE *stream); 
//Return:          returns nonnegative on success or EOF on failure. 

  #include <stdio.h>
  #include <stdlib.h>

  int main(void)
  {
    FILE *fp;

    if((fp=fopen("test", "wb"))==NULL) {
      printf("Cannot open file.\n");
      exit(1);
    }
 
    fputs("this is a test", fp);
    fclose(fp);
  }

freopen: associates an existing stream with a different file

   
//Header file:     #include <stdio.h>  
//Declaration:     FILE *freopen(const char *fname, const char *mode, FILE *stream); 
//Return:          returns a pointer to stream on success or a null pointer on failure. 

//Legal Values for the mode Parameter
   
//Mode             Meaning
//"r":             Open text file for reading 
//"w":             Create a text file for writing 
//"a":             Append to text file 
//"rb":            Open binary file for reading 
//"wb":            Create binary file for writing 
//"ab":            Append to a binary file 
//"r+":            Open text file for read/write 
//"w+":            Create text file for read/write 
//"a+":            Open text file for read/write 
//"rb+" or "r+b":  Open binary file for read/write 
//"wb+" or "w+b":  Create binary file for read/write 
//"ab+" or "a+b":  Open binary file for read/write 

  #include <stdio.h>
  #include <stdlib.h>

  int main(void)
  {
    FILE *fp;

    printf("This will display on the screen.\n");

    if((fp=freopen("OUT", "w" ,stdout))==NULL) {
      printf("Cannot open file.\n");
      exit(1);
    }

    printf("This will be written to the file OUT.");

    fclose(fp);

    return 0;
  }

fseek: moves the file position pointer

   
//Header file:     #include <stdio.h>  
//Declaration:     int fseek(FILE *stream, long int offset, int origin); 
//Return:          zero on success or nonzero on failure. 

//'origin' must be one of:
    
//Name       Meaning
//SEEK_SET:  Seek from start of file 
//SEEK_CUR:  Seek from current location 
//SEEK_END:  Seek from end of file 


  #include <stdio.h>
  #include <stdlib.h>

  struct fullname {
    char firstName[40];
    char lastName[10];
  } info;

  int main(void){
    FILE *fp;

    if((fp=fopen("test", "rb")) == NULL) {
      printf("Cannot open file.\n");
      exit(1);
    }

    int client_num = 10;

    /* find the proper structure */
    fseek(fp, client_num*sizeof(struct fullname), SEEK_SET);

    /* read the data into memory */
    fread(&info, sizeof(struct fullname), 1, fp);

    fclose(fp);
  }

ftell: returns the value for the file position pointer

    
//Header file:     #include <stdio.h>  
//Declaration      long int ftell(FILE *stream); 
//Return:          returns -1 on failure. 

   #include <stdio.h>
   #include <stdlib.h>

   int main(void){
      FILE *fp;

      if((fp=fopen("test", "rb")) == NULL) {
        printf("Cannot open file.\n");
        exit(1);
      }


      int i;
      if((i=ftell(fp)) == -1L)
         printf("A file error has occurred.\n");
      fclose(fp);
   }

getc: reads a character from stream

  
//Header file:     #include <stdio.h>  
//Declaration:     int getc(FILE *stream); 
//Return:          returns EOF on file end or error. 

  #include <stdio.h>
  #include <stdlib.h>

  int main(int argc, char *argv[])
  {
    FILE *fp;
    char ch;

    if((fp=fopen("test", "r"))==NULL) {
      printf("Cannot open file.\n");
      exit(1);
    }

    while((ch=getc(fp))!=EOF) {
      printf("%c", ch);
    }

    fclose(fp);
    return 0;
  }

gets: reads characters from stdin

    

//Header file:     #include <stdio.h>  
//Declaration:     char *gets(char *str); 
//Return:          a null pointer on failure. 
  

  #include <stdio.h>
  #include <stdlib.h>

  int main(void)
  {
    char fname[128];

    printf("Enter filename: ");
    gets(fname);

    printf("%s \n", fname);

    return 0;
  }

         
/*
Enter filename: 321
321
*/
         



putchar: output character to stdout

    

//Header file:     #include <stdio.h>  
//Declaration:     int putchar(int ch); 
//Return:          returns the character written if successful or EOF on error. 

  

#include <stdio.h>
int main(void){

   char *str = "www.google.com";

   for(; *str; str++){
       putchar(*str);
   }
}

remove: delete file by *fname

    

//Header file: #include <stdio.h>  
//Declaration: int remove(const char *fname); 
//Return:      returns zero on success or nonzero on error. 

  #include <stdio.h>

  int main(int argc, char *argv[])
  {
    if(remove("test"))
           printf("Remove Error");

    return 0;
  }

rewind: moves the file position pointer back to the start

    

//Header file:     #include <stdio.h>  
//Declaration:     void rewind(FILE *stream); 

  #include <stdio.h>
  #include <stdlib.h>

  int main(int argc, char *argv[])
  {
    FILE *fp;

    if((fp=fopen("test", "r"))==NULL) {
      printf("Cannot open file.\n");
      exit(1);
    }

    while(!feof(fp)){
        putchar(getc(fp));
    }
    rewind(fp);


    while(!feof(fp)){
        putchar(getc(fp));
    }
    fclose(fp);
  }
//Header file:     #include <stdio.h>  
//Declaration:  void setbuf(FILE *stream, char *buf); 

  
#include <stdio.h>

int main ()
{
  char buffer[BUFSIZ];
  FILE *fp1, *fp2;

  fp1=fopen ("test.txt","w");
  fp2=fopen ("test2.txt","a");

  setbuf ( fp1 , buffer );
  fputs ("This is sent to a buffered stream",fp1);
  fflush (fp1);

  setbuf ( fp2 , NULL );
  fputs ("This is sent to an unbuffered stream",fp2);

  //Set buf to null to turn off buffering.
  //The buffer must be BUFSIZ characters long.
  //BUFSIZ is defined in <stdio.h>.  


  fclose (fp1);
  fclose (fp2);

  return 0;

}

snprintf: identical to sprintf() except that a maximum of num-1 characters will be stored

    

//Header file:     #include <stdio.h>  
//Declaration:     int snprintf(char * restrict buf, size_t num, const char * restrict format, ...) 

#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=snprintf (buffer, 5,"%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a %d char long string\n",buffer,n);
  return 0;
}

sscanf: identical to scanf() except that data is from *buf

  
//Declaration:  int sscanf(const char *buf, const char *format, ...); 
//Return:       the number of variables assigned.   
                A value of zero means that no fields were assigned.  
                EOF indicates an error.  


  #include <stdio.h>

  int main(void)
  {
    char str[80];
    int i;

    sscanf("hello 1 2 3 4 5", "%s%d", str, &i);
    printf("%s %d", str, i);

    return 0;
  }

tmpnam: generates a unique filename

    

 
//Declaration:  char *tmpnam(char *name); 
//Parameters:   *name should be at least L_tmpnam characters long. L_tmpnam is defined in <stdio.h>.  
//Return:       the unique temp name on success or a null pointer on error. 
  #include <stdio.h>

  int main(void)
  {
    char name[40];
    int i;

    for(i=0; i<3; i++) {
      tmpnam(name);
      printf("%s ", name);
    }
    return 0;
  }