gpt4 book ai didi

C 将文件内容从 EOF 复制到 SOF

转载 作者:太空宇宙 更新时间:2023-11-04 06:00:54 30 4
gpt4 key购买 nike

我的程序几乎可以正常工作。预期目的是从末尾读取文件并将内容复制到目标文件。然而让我感到困惑的是 lseek() 方法,所以我应该如何设置偏移量。

目前我的src内容是:
第一行
2号线
第 3 行

目前我在目标文件中得到的是:
3号线
2
2...

据我所知,调用 int loc = lseek(src, -10, SEEK_END); 会将源文件中的“光标”移动到结尾,然后将其从 EOF 偏移到 SOF 10 个字节loc 的值将是我扣除偏移量后的文件大小。然而,在 C 的 7 小时之后,我在这里几乎脑死亡。

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

}

最佳答案

lseek() 不会更改或返回文件大小。它返回的是“光标”设置的位置。所以当你打电话时

loc = lseek(src, offset, SEEK_END);

两次它总是会再次将光标设置到相同的位置。我想你想做这样的事情:

while( loc > 0 )
{
// Read bytes
block = read(src, buffer, 5);

// Write to output file
write(dst, buffer, block);

// Move the pointer again five bytes before the last offset
loc = lseek(src, loc+offset, SEEK_SET);
}

如果行的长度是可变的,您可以改为执行以下操作:

// define an offset that exceeds the maximum line length
int offset = 256;
char buffer[256];
// determine the file size
off_t size = lseek( src, 0, SEEK_END );
off_t pos = size;
// read block of offset bytes from the end
while( pos > 0 ) {
pos -= offset;
if( pos < 0 ) {
//pos must not be negative ...
offset += pos; // in fact decrements offset!!
pos = 0;
}
lseek( src, pos, SEEK_SET );
// add error checking here!!
read(src, buffer, offset );
// we expect the last byte read to be a newline but we are interested in the one BEFORE that
char *p = memchr( buffer, '\n', offset-1 );
p++; // the beginning of the last line
int len = offset - (p-buffer); // and its length
write( dst, p, len );
pos -= len; // repeat with offset bytes before the last line
}

关于C 将文件内容从 EOF 复制到 SOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19523050/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com