简体   繁体   中英

Reading bytes from a file and overwriting the same bytes

I'm using fread to read the contents of a file and I want to over-write the bytes I've just read. So let's say:

fread(buffer, buffersize, 1, FilePointer);

I want to overwrite the exact same bytes that I've just read. The size of buffer varies, but I want to overwrite the exact same amount of bytes I've just read. How can I do that?

Here is how you could do what you want. I use ftell() to remember the starting position so that I don't have to worry about if fread() succeeded or failed.

filePos = ftell(FilePointer);
fread(buffer, buffersize, 1, FilePointer);
fseek(FilePointer, filePos, SEEK_SET);
fwrite(buffer2, buffersize, 1, FilePointer);

Keep in mind that if you are both reading and writing the same file, you need to make sure that you use fflush() or fseek() when you switch from reading to writing or vice versa. If you don't, you get undefined behavior. You can read more about that here.

By the way, if you are looking for faster ways of reading/writing bytes in a file, you might want to look into using mmap() to map your file to memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM