assignment-p-14_v1.c ​
Metadata ​
- Author — Amit Dutta
- Last updated — 12 Dec 2025
- License — MIT License (See the LICENSE file for details)
Problem Statement ​
Problem Statement
Write a C program that opens its own source code file, reads its contents, and then prints the contents to the console.
Source Code ​
Printing the code
To print this file, open it on GitHub and click Raw before printing, or use the Download Raw button above and print directly from that page.
c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *code;
int character, len_upto_dot;
char *FILENAME;
char *dot;
FILENAME = strdup(argv[0]);
if (FILENAME == NULL)
{
printf("\nMemory allocation failed.\n");
return 1;
}
dot = strrchr(FILENAME, '.');
if (dot != NULL)
{
len_upto_dot = dot - FILENAME;
FILENAME[len_upto_dot] = '\0';
}
strcat(FILENAME, ".c");
code = fopen(FILENAME, "r");
if (code == NULL)
{
printf("\nCould not open the source file: %s", FILENAME);
printf("\nPlease ensure the source file is in the same directory as the executable.\n");
free(FILENAME);
return 1;
}
printf("\nReading file: %s", FILENAME);
printf("\n========== %s ==========\n\n", FILENAME);
while ((character = fgetc(code)) != EOF)
{
putchar(character);
}
printf("\n\n========== End of %s ==========\n", FILENAME);
fclose(code);
free(FILENAME);
return 0;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54