如何使用 fseek 设置文件指针
我知道打印此字符串后我的文件指针位于行尾:“xyz”。
我怎样才能把它放到行的开头? (指向x)
offset = ftell(fp);
fseek(fp, offset - sizeof("xyz") , SEEK_SET);
上面似乎不起作用。
我怎样才能做到这一点?
I know my file pointer is at end of the line after printing this string: "xyz".
How can I get it to the start of the line? (pointing to x)
offset = ftell(fp);
fseek(fp, offset - sizeof("xyz") , SEEK_SET);
Above doesn't seem to work.
How can I achieve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在读取/写入“xyz”之前,我会通过发出
beginning = ftell(fp)
来存储偏移量。然后
fseek(fp,开始,SEEK_SET);
这可能吗?
I would store the offset by issuing a
beginning = ftell(fp)
before reading/writing you "xyz".Then
fseek(fp, beginning, SEEK_SET);
Would this be possible?
sizeof("xyz")
将返回 4,因为您有三个字符加上终止 null。您应该使用strlen("xyz")
来代替,或者从 sizeof 结果中减去 1 以解决空值。sizeof("xyz")
will return 4 since you have the three characters plus the terminating null. You should usestrlen("xyz")
instead or subtract one from the sizeof result to account for the null.由于"xyz"
的类型是char const *
,sizeof("xyz")
将返回标准指针的大小,通常为 4 或 8。另请注意,仅当文件以二进制模式打开时,
fseek
才能在 文本 模式下工作,因为这是不可能的告诉底层主机系统上的换行符有多大。另外,最好使用
SEEK_CUR
,因为它会增加相对于当前位置的读/写点。As the type of"xyz"
ischar const *
,sizeof("xyz")
will return the size of a standard pointer, typically 4 or 8.Also note that
fseek
does not work in text mode, only if the file has been opened in binary mode, as it's not possible to tell how big newlines are on the underlying host system.In addition, it's better to use
SEEK_CUR
, as it will more the read/write point relative to the current position.