This blog is under construction

Friday 27 April 2012

fwrite example in C

Header file:
    stdio.h

Synopsis:
     size_t fwrite(const void *ptr, size_t sz, size_t obj, FILE *stream);

Description:
     It takes input from the array ptr and writes obj objects of size sz to the given stream.  Returns number of objects written on success.  Otherwise, it returns a value which is less than obj on error.


fwrite function C example:


  #include<stdio.h>
  #include<string.h>
  #include<stdlib.h>
  #include<errno.h>
  int main() {
        char input[100], *str;
        FILE *fp;
        int len, ret;
        fp = fopen("input.txt", "wb");

        if (fp == NULL) {
                str = strerror(errno);
                perror(str);
                return;
        }
        printf("Enter your input(type quit in newline to exit):\n");
        while(1) {
                fgets(input, 100, stdin);
                len = strlen(input);
                if(strcmp(input, "quit\n") == 0)
                        break;
                ret = fwrite(input, sizeof(char), len, fp);
                if (ret != len) {
                        str = strerror(errno);
                        perror(str);
                        return;
                }
        }
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
  Enter your input(type quit in newline to exit):
  Hello world
  Hello world
  Hello world
  quit
  jp@jp-VirtualBox:~/cpgms/exp$ cat input.txt
  Hello world
  Hello world
  Hello world




No comments:

Post a Comment