assignment-p-14_v1.c (1202B)
1 /* Write a C program that opens its own source code file, reads its contents, and then prints 2 the contents to the console. */ 3 4 #include <stdio.h> 5 #include <string.h> 6 #include <stdlib.h> 7 8 int main(int argc, char *argv[]) 9 { 10 FILE *code; 11 int character, len_upto_dot; 12 char *FILENAME; 13 char *dot; 14 15 FILENAME = strdup(argv[0]); 16 17 if (FILENAME == NULL) 18 { 19 printf("\nMemory allocation failed.\n"); 20 return 1; 21 } 22 23 dot = strrchr(FILENAME, '.'); 24 25 if (dot != NULL) 26 { 27 len_upto_dot = dot - FILENAME; 28 FILENAME[len_upto_dot] = '\0'; 29 } 30 31 strcat(FILENAME, ".c"); 32 33 code = fopen(FILENAME, "r"); 34 35 if (code == NULL) 36 { 37 printf("\nCould not open the source file: %s", FILENAME); 38 printf("\nPlease ensure the source file is in the same directory as the executable.\n"); 39 free(FILENAME); 40 return 1; 41 } 42 43 printf("\nReading file: %s", FILENAME); 44 printf("\n========== %s ==========\n\n", FILENAME); 45 46 while ((character = fgetc(code)) != EOF) 47 { 48 putchar(character); 49 } 50 51 printf("\n\n========== End of %s ==========\n", FILENAME); 52 53 fclose(code); 54 free(FILENAME); 55 56 return 0; 57 }