实现tail

编程之路刚刚开始,错误难免,希望大家能够指出。

自己实现一个tail的功能(使用IO系统调用),完全类似的操作步骤就不实现了,主要是让自己加深了解。

下面的代码不足之处很多,以后有空改正。

 #include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h> #define BUF_SIZE 1024 int GetFileLine(int fd)
{
int iLine = ;
char czBuf[BUF_SIZE+] = {};
while()
{
memset(czBuf,,BUF_SIZE+);
int ret = read(fd,czBuf,BUF_SIZE);
if(ret < )
{
perror("read");
return -;
}
else if(ret == )
{
break;
}
else
{
for(int index = ;index < BUF_SIZE;index++)
{
if(czBuf[index] == '\n')
{
iLine++;
}
}
}
} int ret = lseek(fd,,SEEK_SET);
if(ret < )
{
perror("lseek");
return -;
} return iLine;
} int myTail(int fd,int line)
{
int iLine = GetFileLine(fd);
int ret = -;
char czBuf[BUF_SIZE+] = {};
if(iLine < )
{
return -;
} if(line < iLine)
{
int iStartLine = iLine - line - ;
int iCurLine = ;
int flag = -;
while()
{
memset(czBuf,,BUF_SIZE+);
ret = read(fd,czBuf,BUF_SIZE);
if(ret < )
{
perror("read");
return -;
}
else if(ret == )
{
break;
}
else
{
if(flag == -)
{
for(int index = ;index < BUF_SIZE;index++)
{
if(czBuf[index] == '\n')
{
if(iCurLine == iStartLine)
{
flag = ;
printf("%s",czBuf+index);
break;
}
iCurLine++;
}
}
}
else if(flag == )
{
printf("%s",czBuf);
}
}
}
}
else
{
while()
{
char czBuf[BUF_SIZE] = {};
ret = read(fd,czBuf,BUF_SIZE);
if(ret < )
{
perror("read");
return -;
}
else if(ret == )
{
break;
}
else
{
printf("%s",czBuf);
}
}
}
return ;
} int main(int argc,char *argv[])
{
int fd = open("test.txt",O_RDONLY);
if(fd < )
{
perror("open");
return -;
} int ret = myTail(fd,);
if(ret < )
{
close(fd);
return -;
} close(fd);
return ;
}
上一篇:Windows Phone本地数据库(SQLCE):9、Connection Strings(翻译) (转)


下一篇:[NOIP2015]运输计划 D2 T3 LCA+二分答案+差分数组