模仿tac命令
以前逛兰大开源社区,看到一模仿Linux/Unix下tac命令的文章,感觉思路挺不错,代码实现如下:
/*
*First ,read one ,then push this line to the stack
*Then ,read the next line
*Until read to the end
*At last pop the data from stack
*/
#include <stdio.h>
#include <error.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#define MAXLINE 8192
struct stacklink
{
char *linebuf;
struct stacklink *next;
};
struct stacklink *head;
//push the line data to the stack
void creatstack(struct stacklink * buf)
{
if(head->next==NULL){
head->next=buf;
buf->next=NULL;
}
else{
buf->next=head->next;
head->next=buf;
}
}
//pop the data ,and print the result
void tacshow()
{
struct stacklink *tmp;
tmp=head->next;
if(head->next!=NULL)
while(tmp!=NULL)
{
printf("%s",tmp->linebuf);
tmp=tmp->next;
}
}
int main(int argc,char *argv[])
{
FILE *fp;
struct stacklink *buf;
char ch,tmp_array[MAXLINE];
int i;
head=malloc(sizeof(struct stacklink));
size_t n;
/*
*this is only aupport one parameters
*It can easily support for more than one parameters
*Such as:
*put the below codes to "for" loop,and read the filename argv[i] will
*be ok!
*/
if(argc!=2)
{
perror("Please input the file's name\n");
}
if((fp=fopen(argv[1],"rb"))==NULL)
{
perror("open error\n");
}
buf=malloc(sizeof(struct stacklink));
buf->linebuf=NULL;
while((getline(&buf->linebuf,&n,fp))!=EOF){
creatstack(buf);
buf=malloc(sizeof(struct stacklink));
}
fclose(fp);
tacshow();
free(head);
free(buf);
return 0;
}