假设存在push
如下,你可以使用如下的recv_stack
andsend_stack
函数。错误报告是基本的,但它的结构很容易改进。
void push(int k, struct stack* s);
#define ERR_SUCCESS 0
#define ERR_PROTOCOL 1
void send_int(FILE* f, int k)
{
fprintf(f, "%d", k);
}
void send_stack(FILE* f, const struct stack* s)
{
int flag = 0;
const struct list* a = &s->l;
fprintf(f, "{ ");
while(a != NULL)
{
send_int(f, a->Element);
a = a->next;
if(flag)
{
fprintf(f, ", ");
}
flag = 1;
}
fprintf(f, " }\n");
}
#define RECV_READ_LBRACE 1
#define RECV_READ_INTEGER 2
#define RECV_CONT_INTEGER 3
#define RECV_FINAL 4
int
recv_stack(FILE* f, struct stack* s)
{
int state = RECV_READ_LBRACE;
int error = ERR_SUCCESS;
int ax = 0;
do {
char c = fgetc(f);
switch(state)
{
case RECV_READ_LBRACE:
if(c == '{')
{
state = RECV_READ_INTEGER;
}
else
{
state = RECV_FINAL;
error = ERR_PROTOCOL;
}
break;
case RECV_READ_INTEGER:
if(isdigit(c))
{
state = RECV_CONT_INTEGER;
ax = c - '0';
}
else if(c != ' ')
{
state = RECV_FINAL;
error = ERR_PROTOCOL;
}
break;
case RECV_CONT_INTEGER:
if(isdigit(c))
{
ax *= 10;
ax += c - '0';
}
else if(c == ',')
{
state = RECV_READ_INTEGER;
push(ax, s);
}
else if(c == '}')
{
state = RECV_FINAL;
push(ax, s);
}
else
{
state = RECV_FINAL;
error = ERR_PROTOCOL;
}
break;
}
} while(state != RECV_FINAL);
return error;
}