This blog is under construction

Wednesday 31 July 2013

C program to take input from a file

Write a C program to take input from a file.


  #include <stdio.h>
  #include <string.h>
  #define MAX 256

  int main() {
        FILE *fp;
        int num1, num2, res, ch;
        char filename[MAX];

        /* get the input file name from the user */
        printf("Enter your input file name:");
        fgets(filename, MAX, stdin);
        filename[strlen(filename) - 1] = '\0';


        /* open the input file in read mode */
        fp = fopen(filename, "r");

        /* error handling */
        if (!fp) {
                printf("Unable to open input file!!\n");
                return 0;
        }

        /* find the sum, diff, product & division value */
        while (!feof(fp)) {

                /* fetch the input values from the given file */
                fscanf(fp, "%d%d%d", &ch, &num1, &num2);

                /* end of file */
                if (feof(fp))
                        continue;

                /* addition, subtraction, multiply and divide operations */
                switch (ch) {
                        case 1:
                                printf("Sum of %d and %d is %d\n",
                                                num1, num2, num1 + num2);
                                break;

                        case 2:
                                printf("Difference between %d and %d is %d\n",
                                                num1, num2, num1 - num2);
                                break;

                        case 3:
                                printf("Product of %d and %d is %d\n",
                                                num1, num2, num1 * num2);
                                break;

                        case 4:
                                printf("Division of %d and %d is %d\n",
                                                num1, num2, num1 / num2);
                                break;

                        default:
                                printf("wrong option!!\n");
                                break;
                }
        }

        /* closing the input file */
        fclose (fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat data.txt 
  1 100 200
  2 200 100
  3 100 400
  4 900 100

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input file name :data.txt
  Sum of 100 and 200 is 300
  Difference between 200 and 100 is 100
  Product of 100 and 400 is 40000
  Division of 900 and 100 is 9






SEE ALSO

    No comments:

    Post a Comment