hari
hari

Reputation: 9733

how to set file pointer with fseek

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?

Upvotes: 0

Views: 4067

Answers (3)

Lindydancer
Lindydancer

Reputation: 26094

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.

Upvotes: 0

David Paxson
David Paxson

Reputation: 553

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.

Upvotes: 1

M'vy
M'vy

Reputation: 5774

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?

Upvotes: 1

Related Questions