用C语言实现的严蔚敏版《数据结构》栈与队列一章中的“行编辑程序”
因为用了引用,应该在C++编译环境编译执行。
#include
#include
typedef char SElemType; //stack element
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 2
FILE *fp; //定义文件指针
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//-----基础操作的函数原型说明---
int InitStack(SqStack &S)
{
S.base = (SElemType *)malloc(STACK_INIT_SIZE *sizeof(SElemType));
if(!S.base)exit(OVERFLOW); //存储分配失败
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
int DestropStack(SqStack &S)
{
free(S.base);
S.base = NULL;
S.top = NULL;
S.stacksize = 0;
return OK;
} //DestropStack
int ClearStack(SqStack &S)
{
S.top = S.base;
return OK;
} //ClearStack
int GetTop(SqStack S, SElemType &e)
{
if(S.top == S.base) return ERROR;
e = *(S.top -1);
return OK;
} //GetTop
int Push(SqStack &S, SElemType e)
{
if(S.top -S.base >=S.stacksize)
{
S.base = (SElemType *)realloc(S.base,
(S.stacksize +STACKINCREMENT)*sizeof(SElemType));
if(!S.base)exit(OVERFLOW);
S.top = S.base +S.stacksize;
S.stacksize +=STACKINCREMENT;
}
*S.top++ = e;
return OK;
} //Push
int Pop(SqStack &S, SElemType &e)
{
if(S.top == S.base)return ERROR;
e = *--S.top;
return OK;
} //Pop
int StackTraverse(SqStack S,int (*visit)(SElemType ))
{
while(S.top > S.base)
visit(*S.base++);
printf("\n");
return OK;
}
//将字符送至fp所指的文件中
int copy(SElemType c)
{
fputc(c,fp);
return OK;
}
void LineEdit()
{
SqStack S;
char ch, c;
InitStack(S);
printf("请输入一个文本文件,ctrl+z结束输入,#退格,@清空当前行:\n");
ch = getchar();
while(ch !=EOF)
{
while(ch != EOF && ch !='\n')
{
switch(ch)
{
case '#': Pop(S,c);
break;
case '@': ClearStack(S);
break;
default : Push(S,ch);
break;
}
ch = getchar();
}
StackTraverse(S,copy);
ClearStack(S);
fputc('\n',fp);
if(ch!=EOF) ch = getchar();
}
DestropStack(S);
}
int main()
{
fp = fopen("1.txt","w");
if(fp)
{
LineEdit();
fclose(fp);
}
else
{
printf("建立文件失败!\n");
}
system("pause");
return 0;
}
输出效果:
请输入一个文本文件,ctrl+z结束输入,#退格,@清空当前行:
whli##ilr#e(s#*s)
outcha@putchar(*s=#++);
请按任意键继续. . .
下面是"1.txt"中的内容:
while(*s)
putchar(*s++);
*/