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

标签 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”。我希望能够向后打印该单词。

最佳答案

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

还需要进一步寻找。另外 lseek( ..., 1, SEEK_END); 可能应该是 lseek(...,0, SEEK_END); 我对于寻求超越文件。

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

关于c - 使用 lseek() 打印出重复的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32554025/

相关文章:

c - 是否可以在 GCC/GNU C 中编写一个 _Static_assert 来验证编译时内存中位字段的布局?

c - 来自文本文件c代码的邻接矩阵

c++ - 连接多个字符

android - 如何清除蓝牙输入流缓冲区

php - 如何使用PHP写入串口?缓冲有问题

c++ - 共享库中的符号

c - 在两个函数中使用 strtok() 安全吗?

c - 理解 c 中的 typedef

matlab - matlab中的writematrix命令可以指定小数位数吗?

c - 有界缓冲区程序引入数据竞争 : Where are they? 如何修复它们?