假设我们有一个文件“x”,其中包含字符串“0123456789”。
我们打开文件并有一个文件描述符fd
。
我们可以执行read(fd, some_buffer, 5)
从文件中读取5个值到缓冲区中。
同样,我们可以使用 fseek 将指针移动到文件中的各个条目。
我的问题是,当我们使用带有正偏移量的 SEEK_END
时,fseek
的行为是什么?此行为是否未定义,或者它是否环绕到文件内容的前面?
那么如果我们执行fseek(fd, 5, SEEK_END)
,指针现在会指向哪里?
最佳答案
My question is, what is the behavior of
fseek
when we usedSEEK_END
with a positive offset? Is this behavior undefined, or does it wrap around to the front of the contents of the file?
如果流是文本流,那么就 C 语言而言,行为是未定义的,因为标准指定:
For a text stream, either
offset
shall be zero, oroffset
shall be a value returned by an earlier successful call to theftell
function on a stream associated with the same file andwhence
shall beSEEK_SET
.
(C2011, 7.21.9.2/4)。没有为非零偏移量和 SEEK_END
的组合定义任何行为。
对于二进制流,
the new position, measured in characters from the beginning of the file, is obtained by adding offset to the position specified by
whence
( C2011, 7.21.9.2/3 ),所以不,它绝对不会环绕。标准接着说
A binary stream need not meaningfully support
fseek
calls with a whence value ofSEEK_END
,因此您所描述的此类调用可能(明确)会失败,并返回错误代码。然而,如果它确实成功了——并且通过某些实现,可以预期对某些流这样做——那么它会导致文件位置超过文件末尾。尝试在这样的位置读取应该具有与该位置位于 EOF 相同的结果。尝试写入的行为取决于文件的打开模式(对以追加模式打开的流的所有写入都会转到文件的当前末尾)和实现。
例如,在 POSIX 系统上,系统的 C 实现被指定为允许将与常规文件关联的流定位到文件末尾之后,并且在这样的位置成功写入的行为就像将值为 0 的字节写入一样该位置与文件前一个结尾之间的所有位置。此外,POSIX 在实践中并不区分文本流和二进制流。
关于c - 带有 SEEK_END 和正偏移量的 fseek 的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55734105/