-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindentation.cpp
More file actions
139 lines (132 loc) · 2.83 KB
/
Copy pathindentation.cpp
File metadata and controls
139 lines (132 loc) · 2.83 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <stdio.h>
#define MAX_SIZE 20
#define MAX_LINE_LENGTH 100
struct Stack
{
int stack[MAX_SIZE];
int top;
};
void push(struct Stack *st, int num)
{
if (st->top < MAX_SIZE - 1)
{
st->stack[++(st->top)] = num;
}
// else
// {
// printf("Stack overflow");
// }
}
int getLastElement(struct Stack *st)
{
if (st->top > -1)
{
return st->stack[(st->top)];
}
else
{
return -1;
}
}
int pop(struct Stack *st)
{
if (st->top > -1)
{
return st->stack[(st->top)--];
}
else
{
// printf("Stack underflow\n");
return -1;
}
}
void displayStack(struct Stack *st)
{
if (st->top > -1)
{
int m = st->top;
while (m > -1)
{
printf("%d ", st->stack[m]);
m--;
}
}
else
{
// printf("Stack underflow\n");
}
}
int getNumberOfSpaces(char a[])
{
int spaces = 0;
int i = 0;
while (a[i] == '\t' || a[i] == ' ')
{
if (a[i] == '\t')
spaces = spaces + 4;
else
spaces = spaces + 1;
i++;
}
return spaces;
}
int checkIndentation(FILE *file)
{
char a[MAX_LINE_LENGTH];
struct Stack s;
s.top = -1;
int lineNumber = 1;
fgets(a, MAX_LINE_LENGTH, file);
int currentSpaces = getNumberOfSpaces(a);
push(&s, currentSpaces);
while (fgets(a, MAX_LINE_LENGTH, file))
{
lineNumber++;
// displayStack(&s);
// printf("\n");
int count = getNumberOfSpaces(a);
if (count > currentSpaces)
{
push(&s, count);
currentSpaces = count;
//printf("Current Spaces: %d \n", currentSpaces);
}
else if (count < currentSpaces)
{
//pop current spaces
pop(&s);
//get the previous spaces
int prev = getLastElement(&s);
if (prev != -1 && prev != count)
{
// printf("Prev: %d Current: %d", prev, count);
return lineNumber;
}
currentSpaces = prev;
//printf("Current Spaces: %d \n", currentSpaces);
}
}
return -1;
}
int main()
{
FILE *filepointer;
char file_name[25];
printf("Enter the name of the file you want to check.\n");
gets(file_name);
filepointer = fopen(file_name, "r");
if (filepointer == NULL)
{
printf("Error opening file");
}
else
{
int result = checkIndentation(filepointer);
if (result == -1)
{
printf("File is OK");
}
else
printf("Error at line %d, line is not indented", result);
}
}