This blog is under construction

Monday 29 July 2013

C program to print the source code of itself as output

Write a C program to print own source code.


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

  int main() {
        int ch;
        FILE *fp;
        char filename[MAX];

        /* get the input file name */
        printf("Enter your 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 the input file!!\n");
                return 0;
        }

        /* prints the source code */
        printf("\n\nPlease find my source code below:\n");
        while (!feof(fp)) {
                int ch = fgetc(fp);

                if (ch != EOF) {
                        printf("%c", ch);
                }
        }

        /* close the opened file */
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your file name: source.c

  Please find my source code below:
  /* C program to print the source code of itself as output */
  #include <stdio.h>
  #include <string.h>
  #define MAX 256

  int main() {
int ch;
FILE *fp;
char filename[MAX];

/* get the input file name */
printf("Enter your 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 the input file!!\n");
return 0;
}

/* prints the source code */
printf("\n\nPlease find my source code below:\n");
while (!feof(fp)) {
int ch = fgetc(fp);

if (ch != EOF) {
printf("%c", ch);
}
}

/* close the opened file */
fclose(fp);
   return 0;
  }






SEE ALSO

    No comments:

    Post a Comment