【发布时间】:2013-10-22 16:12:02
【问题描述】:
我的程序几乎可以正常运行。预期目的是从末尾读取文件并将内容复制到目标文件。然而更让我困惑的是lseek() 方法,所以我应该如何设置偏移量。
我的src目前的内容是:
1号线
2号线
3号线
目前我在目标文件中得到的是:
3号线
2
e 2...
据我了解,调用int loc = lseek(src, -10, SEEK_END); 会将源文件中的“光标”移动到末尾,然后将其从 EOF 偏移到 SOF 10 个字节,并且 loc 的值将是我扣除偏移后的文件大小.然而,经过 7 小时的 C 学习后,我几乎脑死了。
int main(int argc, char* argv[])
{
// Open source & source file
int src = open(argv[1], O_RDONLY, 0777);
int dst = open(argv[2], O_CREAT|O_WRONLY, 0777);
// Check if either reported an erro
if(src == -1 || dst == -1)
{
perror("There was a problem with one of the files.");
}
// Set buffer & block size
char buffer[1];
int block;
// Set offset from EOF
int offset = -1;
// Set file pointer location to the end of file
int loc = lseek(src, offset, SEEK_END);
// Read from source from EOF to SOF
while( loc > 0 )
{
// Read bytes
block = read(src, buffer, 1);
// Write to output file
write(dst, buffer, block);
// Move the pointer again
loc = lseek(src, loc-1, SEEK_SET);
}
}
【问题讨论】:
-
当然,整个方法仅适用于固定大小的记录,而您的示例数据看起来像一个文本文件,其中每一行的大小可能不同。 (更不用说,即使行是固定长度的,由于换行符和空格,您的 -5 偏移量也是错误的。)
-
@Kevin 我知道,我的解决方案是简单地逐字节读取,但这会导致正确的输出,但是每个单词都被颠倒了,所以我会得到 3eniL ...等
-
您可以使用 linux.die.net/man/3/strrchr 执行此操作 while (NULL != tmp=strrchr(buffer, '\n')) write(dst,tmp, strlen(tmp));