- 论坛徽章:
- 0
|
写了个c代码.
test.c:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
/*1 for null*/
#define bufsize 4097
extern int errno;
static char buf[bufsize];
static char *mystrtok(char*);
/*返回第一个数字串*/
static char *mystrtok(char *str){
register int pos =0;
char *ptr = NULL;
while(str[pos]!='\0'){
if(str[pos]>='0'&&str[pos]<='9') {
if(ptr==NULL) ptr = &str[pos];
}else{
str[pos] = '\0';
if(ptr!=NULL) break;
}
pos++;
}
return ptr;
}
int main(int argc,char *argv[]){
int fd;
register int len;
if(argv[1]){
fd = open(argv[1],O_RDONLY);
if(fd<=0) {
fprintf(stderr,"can not open file:%s\n",argv[1]);
return -1;
}
}else{
fd = fileno(stdin);
}
memset(buf,0,bufsize);
while((len=read(fd,buf,bufsize-1))>0){
/*防止截断了数字串*/
if(len==(bufsize-1)){
register int i=0;
while(buf[len-i-1]>='0'&&buf[len-i-1]<='9'){
i++;
}
if(i>0&&i<len){
buf[len-i] = '\0';
if(lseek(fd,-i,SEEK_CUR)==-1){
printf("seek error,errno is :%d\n",errno);
close(fd);
return -1;
}
}
}
char *ptr,*cursor=buf;
while((ptr=mystrtok(cursor))!=NULL){
/*这里可以插入链表,进行排序,少的话,用快速排序法,多的话,用堆排序或并归排序*/
fprintf(stdout,"%s\n",ptr);
cursor = strlen(ptr)+ptr+1;
}
memset(buf,0,bufsize);
}
close(fd);
return 0;
}
|
使用方法
[root@test1 c]# gcc test.c -o test
[root@test1 c]# ./test <in.txt >out.txt
不知道速度如何. |
|