使用lseek()打印出重复的字符

时间:2015-09-13 20:04:58

标签: c file buffer lseek

char x[3];
char buff, c;
x[0]='y';
int offset, i;
int fd;

fd = open("test1.txt", O_RDONLY);
if(fd==-1){ printf("Error on fopen."); exit(1); }

offset = lseek(fd, 1, SEEK_END);
printf("Size of file is: %d. \n", offset);

for(i=offset-1; i>=0; i--)
{
  c = read(fd, &buff, 1);
  printf("The character is: %c. \n", c);
}

close(fd);

运行它给了我。

Size of file is: 6. 
The character is: . 
The character is: . 
The character is: . 
The character is: . 
The character is: . 
The character is: . 

测试文件只包含单词" TEST"。我希望能够向后打印这个词。

1 个答案:

答案 0 :(得分:0)

read读取当前位置,并将当前位置向前移动读取的数量。

需要进一步寻求。同样lseek( ..., 1, SEEK_END);可能应该是lseek(...,0, SEEK_END);我会因为寻求超出档案而感到不舒服。

for( i = ... ) {
    lseek(fd, size - i, SEEK_BEGIN );
    read(...);
}