开发者

How to write to specific offset in empty file

I have a file in which I read in data. Suppose the file has the string "abcdefghij". Now, I'm going to be reading from the file at random times from different processes and they store that byte and offset somewhere. For instance, I save 'c' as my character with an offset of '3' because that is its loca开发者_如何学编程tion. For reference, I've been using lseek to get the offset in my files.

Next, I want to write this to a new file. Is it possible to write to a specific offset in an empty file? So, I want to write 'c' to position '3' in the file and then another process will write 'j' to the file at position 10.


#include <stdio.h>

int main ()
{
    FILE * f = fopen ("/tmp/x.txt", "w");

    fseek (f, 3, SEEK_SET);
    fwrite ("c", 1, 1, f);

    fseek (f, 10, SEEK_SET);
    fwrite ("j", 1, 1, f);

    fclose (f);
}

When this runs, the hexdump of /tmp/x.txt is

00 00 00 63 00 00 00 00  00 00 6a          | ...c.... ..j

fseek is based on lseek which is capable of recognising "holes" in files (ranges of zeroes which haven't been written yet) but the underlying file system needs to support this.

It's not brilliantly clear to me from the manpage that the holes are strictly required to be zeroes, but that seems to be the case in practice.


Look into ftello. Then use fwrite. You can also use lseek/write, if you're using fd's instead of FILE*s.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜