Main function.
12{
13 int position = 0, num_bad_chars = 0;
14 int num_digits = 4;
15 char ch;
16 unsigned char num, num_prev;
17 unsigned char *
buffer = NULL;
18 long long int prod = 1, max_prod = 0;
19
20
21
22
23
24 if (argc == 2)
25 num_digits = atoi(argv[1]);
26
27
30 {
31 perror("Unable to allocate memory for buffer");
32 return -1;
33 }
34
35
36 FILE *fp = fopen("digits.txt", "rt");
37 if (!fp)
38 {
39 perror("Unable to open file");
41 return -1;
42 }
43
44
45 do
46 {
47
48 ch = getc(fp);
49
50
51
52
53 if (ch < 0x30 || ch > 0x39)
54 {
55 num_bad_chars++;
56
57 continue;
58 }
59 else if (num_bad_chars > 0)
60 num_bad_chars--;
61
62 num = ch - 0x30;
64
65
66
67
69
70
71
72
73
74 buffer[num_digits - 1] = num;
75
76 if (num_prev != 0)
77 {
78
79
80
81
82 prod /= num_prev;
83 prod *= num;
84 }
85 else
86 {
87 prod = 1;
88 for (int i = 0; i < num_digits; i++)
89 {
91 {
92 prod = 0;
93 break;
94 }
96 }
97 }
98
99
100 if (prod > max_prod)
101 {
102 max_prod = prod;
103 position = ftell(fp) - num_bad_chars - num_digits - 1;
104 }
105 } while (!feof(fp));
106
107 printf("Maximum product: %lld\t Location: %d^th position\n\t", max_prod,
108 position);
109 fseek(fp, position,
110 SEEK_SET);
111
112 for (; num_digits > 0; num_digits--)
113 {
114 char ch = getc(fp);
115
116 if (ch < 0x30 || ch > 0x39)
117 continue;
118 if (num_digits > 1)
119 printf("%c x ", ch);
120 else
121 printf("%c = %lld\n", ch, max_prod);
122 }
123
124 fclose(fp);
126
127 return 0;
128}
#define free(ptr)
This macro replace the standard free function with free_dbg.
Definition malloc_dbg.h:26
#define calloc(elemCount, elemSize)
This macro replace the standard calloc function with calloc_dbg.
Definition malloc_dbg.h:22
struct used to store character in certain times
Definition min_printf.h:35