gpt4 book ai didi

c - 在 C 中不使用 fseek 移动文件位置

转载 作者:太空宇宙 更新时间:2023-11-04 08:42:45 25 4
gpt4 key购买 nike

如何在 C 中将文件位置后移 x 字节?

我不想使用 fseek(),因为我正在使用 open(fd, buf, buflength) 读取文件行,而不是 fopen().

我非常想避免将整个文件读入内存。

我想做的基本上是:

  1. 读取 X + A = Y 字节。
  2. 对前 X 个字节做一些事情。
  3. 将文件指针向后移动A字节。
  4. 从那里读取 Y 个字节。

除了第 3 步,我知道如何做所有事情。有人知道怎么做吗?

最佳答案

根据 http://rabbit.eng.miami.edu/info/functions/unixio.html你可以使用 lseek:

int lseek(int fd, int position, int startpoint)
include: <unistd.h>
Sets the file position effective for the next read or write operation.
fd = file descriptor as returned by open
position = position within file:
number of bytes between startpoint and the desired position, may be negative.
startpoint = location in file that position is relative to, one of:
SEEK_SET Position is number of bytes from beginning of file
SEEK_END Position is number of bytes after end of file
SEEK_CUR Position is number of bytes after current position
returns <0 for error,
or resulting file position relative to beginning of file.

Moving beyond the end of the file is permitted; the file is extended in length
only if a write occurs beyond the current end of file. Moving before the
beginning of a file is not permitted. A write operation after a move only
overwrites the number of bytes actually written.

关于c - 在 C 中不使用 fseek 移动文件位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22924863/

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