This blog is under construction

Friday 27 April 2012

fscanf example in C

Header file:
    stdio.h

Synopsis:
     int fscanf(FILE *stream, const char *format, ...);

Description:
    Performs input format conversion.  It reads the input from the stream and do format conversion.  Then, it will assign those converted values to the subsequent arguments of format correspondingly.  And it returns the number of inputs successfully matched and assigned with values.


fscanf function C example:


  #include<stdio.h>
  int main() {
        char str[100];
        int num1, num2, res;
        FILE *fp;
        fp = fopen("input.txt", "r");
        if (!fp) {
                printf("Unable to read the file\n");
                return;
        }
        /* reads input from the file input.txt */
        fscanf(fp, "%s%d%d", str, &num1, &num2);
        res = num1 + num2;
        printf("%s %d\n", str, res);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/exp$ cat input.txt
  Output:
  100 200
  jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
  Output: 300



No comments:

Post a Comment