我需要用C语言编写一个程序,使用open,read,write,close,lseek等基本函数打印出最后五行文件。我的代码到目前为止:在Linux下打印最后5行文件在C中使用
int main(int argc, char *argv[]){
int fd1=open(argv[1], O_RDONLY);
char c;
int currPos = lseek(fd1,-2,SEEK_END);
while(currPos != -1){
read(fd1,&c,sizeof(c));
currPos--;
currPos=lseek(fd1,currPos,SEEK_SET);
if (c == '\n'){
}
}
return 0;
}
任何人都可以帮助我吗?我想我需要将这些字符存储在数组中,然后向后打印,但我不知道如何。
你的代码效率很低。如果可能的话,'read'应该与几千字节的缓冲区一起使用,并且您应该*总是*使用它的返回值并检查错误! – 2014-10-22 13:27:23