开发者

how to set file pointer with fseek

开发者 https://www.devze.com 2023-02-17 18:45 出处:网络
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)

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开发者_JAVA百科);

Above doesn't seem to work.

How can I achieve that?


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") will return 4 since you have the three characters plus the terminating null. You should use strlen("xyz") instead or subtract one from the sizeof result to account for the null.


As the type of "xyz" is char 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号