/*** file stack.c ***/
#include "spublic.h"
#include "sprivate.h"
int push(element the_data)
{
int status = -1;
status = priv_push(the_data);
return(status);
} /* ends push */
int priv_push(element new_data)
{
char aline[L];
int status = 1;
FILE *stack_file,
*temp_file;
/* write new data to temp file */
if((temp_file =
fopen(TEMPFILE, "wt")) == NULL){
printf("\nERROR Couldnt open %s",
TEMPFILE);
status = -1;
} /* ends if fopen failed */
sprintf(aline, "\n%d", new_data);
fputs(aline, temp_file);
/* copy stack to temp */
if((stack_file =
fopen(STACKFILE, "rt")) == NULL){
printf("\nERROR Couldnt open %s",
STACKFILE);
status = -1;
} /* ends if fopen failed */
while(fgets(aline, L, stack_file))
fputs(aline, temp_file);
fclose(stack_file);
fclose(temp_file);
/* Copy back to stack file */
if((temp_file =
fopen(TEMPFILE, "rt")) == NULL){
printf("\nERROR Couldnt open %s",
TEMPFILE);
status = -1;
} /* ends if fopen failed */
if((stack_file =
fopen(STACKFILE, "wt")) == NULL){
printf("\nERROR Couldnt open %s",
STACKFILE);
status = -1;
} /* ends if fopen failed */
while(fgets(aline, L, temp_file))
fputs(aline, stack_file);
fclose(stack_file);
fclose(temp_file);
return(status);
} /* ends priv_push */
element pop()
{
element result = -1;
result = priv_pop();
return(result);
} /* ends pop */
element priv_pop()
{
char aline[L];
element result = 1;
FILE *stack_file,
*temp_file;
int status = 0;
/* Read first line from stack */
if((stack_file =
fopen(STACKFILE, "rt")) == NULL){
printf("\nERROR Couldnt open %s",
STACKFILE);
result = -1;
} /* ends if fopen failed */
fgets(aline, L, stack_file);
result = atoi(aline);
/* Copy the rest to temp */
if((temp_file =
fopen(TEMPFILE, "wt")) == NULL){
printf("\nERROR Couldnt open %s",
TEMPFILE);
status = -1;
} /* ends if fopen failed */
while(fgets(aline, L, stack_file))
fputs(aline, temp_file);
fclose(stack_file);
fclose(temp_file);
/* Copy back to stack file */
if((temp_file =
fopen(TEMPFILE, "rt")) == NULL){
printf("\nERROR Couldnt open %s",
TEMPFILE);
status = -1;
} /* ends if fopen failed */
if((stack_file =
fopen(STACKFILE, "wt")) == NULL){
printf("\nERROR Couldnt open %s",
STACKFILE);
status = -1;
} /* ends if fopen failed */
while(fgets(aline, L, temp_file))
fputs(aline, stack_file);
fclose(stack_file);
fclose(temp_file);
return(result);
} /* ends priv_pop */
/* End of File */