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