Checking a Text File for Proper Parentheses/Braces Nesting (Beginner)
Hello again,
Thanks to all who have helped me with my problems in the past.
Today, I am working on a problem that asks to check whether a series of parentheses or braces is properly nested.
I seem to have it working, but I am wondering if folks could help me on style and welcome any other comments/suggestions (i.e. bugs, efficiency, etc).
Code:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define STACK_SIZE 4
/* external variables */
char contents[STACK_SIZE];
int top = 0;
char ch;
void make_empty(void);
bool is_empty(void);
bool is_full(void);
void pop(void);
void push(char ch);
void stack_overflow(void);
void stack_underflow(void);
int main(int argc, char *argv[]){
FILE *fp;
printf("Checking %s file: ", argv[1]);
fp = fopen(argv[1], "r+");
while ((ch = fgetc(fp)) != EOF){
if (ch == '(' || ch == '{')
push(ch);
else if (ch == ')' || ch == '}')
pop();
}
if (is_empty() == true)
printf("\n\nParentheses/braces are nested properly.\n\n");
if (is_empty() == false)
printf("\n\nParentheses/brances are NOT nested properly.\n\n");
return 0;
}
void make_empty(void)
{
top = 0;
}
bool is_empty(void)
{
return top == 0;
}
bool is_full(void)
{
return top >= STACK_SIZE;
}
void stack_overflow(void){
printf("Stack Overflow!\n");
exit(EXIT_FAILURE);
}
void stack_underflow(void){
printf("Stack Underflow!\n");
exit(EXIT_FAILURE);
}
void push(char ch)
{
if (is_full())
stack_overflow();
else
contents[top++] = ch;
}
void pop(void)
{
if (is_empty())
stack_underflow();
else
contents[--top] = 0;
}