简体   繁体   中英

printing last 5 lines of file in C in Linux

I need to write a program in C, that prints out last five lines of file by using basic functions like open, read, write, close, lseek. My code so far:

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;
}

Can anybody help me? I think I need to store those characters in array and then print it backwards, but I don't know how.

Why not count the number of characters read while reading back to the fifth newline (call that n ) and then do a read of n characters? You don't need to store the data, it's already stored in the file.

Inside the if statement you can count how many '\\n' characters you encounter from the end of your file. When you encounter the 6th end-of-line, you know you are at the end of the 6-th-from-the-end line (assuming that the last line also contains an end-of-line character at the end) , so you just print from that point to the end of the file.

You do not need to save the characters in an array, since they are already saved in your file. You can just do (after your while loop):

int i=read(fd1,&c,1);
while(i){
    printf("%c",c);
    i = read(fd1,&c,1);
}

It may not be the most efficient way to do it, but it should do the trick.

Note: There is no need to write sizeof(c) , since c is a char , and char s are always 1 byte long. Also, you should always check the return value of read , you never know when something goes wrong in your system and your program crashes because of a read gone wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM