简体   繁体   中英

Can you create undefined data by fseeking past EOF?

If you use fseek to go past the end of a file and then append data after the EOF, would the data in between the EOF and what you wrote be undefined?

For example in the code below, would there be 10 bytes of undefined data in the written file because of randomLengthPastEOF ?

unsigned char *someText= "ExampleText";
int length = 11;
int randomLengthPastEOF  = 10;

FILE *output = fopen("/Example/FilePath", "wb");
fseek(input, randomLengthPastEOF ,SEEK_END);
fwrite(someText, 1, length, output);

I can't find a reference any where to what might happen so I assume it is undefined.

POSIX defines data in between to be zero bytes: http://www.unix.com/man-page/POSIX/3posix/fseek/

The fseek() function shall allow the file-position indicator to be set beyond the end of existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap.

It'll all be zeros. In fact, if you skip far enough to skip whole blocks UNIX will make what's called a sparse file, only the blocks you have written to are allocated, and if you later try to read from the blocks that were never written to, it doesn't read the disk, it just pretends there's a block of all zeros and returns the part of that you asked for.

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