seek系列功能就像看片時,順轉或倒轉,在某種時機下還蠻重要的。

input.txt:

1111
2222
3333
4444
5555
6666
7777
8888

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
        FILE* fd;
        char* buf=malloc(5);

        fd=fopen("/home/latrell/temp/ctest/input.txt", "r");
        if(fd==NULL) return 1;

        //一行是5個byte,含最後的換行
        fseek(fd, 20, SEEK_SET); //從頭順轉4行,因此從第5行開始看
        fread(buf, 1, 5, fd);
        printf("read in: %s\n",buf);

        fseek(fd, 5, SEEK_CUR);//從現在的地方,再順轉一行,因此第6行跳過,從第7行開始看
        fread(buf, 1, 5, fd);
        printf("read in: %s\n",buf);

        fseek(fd, -15, SEEK_END);//從最後面開始倒轉3行,用負數表示,因此從第8行到轉到第6行,從第6行開始看
        fread(buf, 1, 5, fd);
        printf("read in: %s\n",buf);

        fclose(fd);
        free(buf);
        return 0;

}

Output:

user-ubuntu:~/temp/ctest$ ./a.out
read in: 5555

read in: 7777

read in: 6666

 

arrow
arrow
    全站熱搜

    kezeodsnx 發表在 痞客邦 留言(0) 人氣()