2

I have a large block of memory in my C program that contains zeros in the middle. I want to save this to disk without converting the values to ASCII. Will writing zeros to a file stream cause a false-negative EOF when I try to read from that file later?

Example:

int x[1024] = {1, 2, 3, 4, 0, 0, 0, 0, 3};
// write x to disk in myfile.bin

Thanks in advance!

3
  • 1
    Not if you use fwrite to write the memory block to a binary file. Next, 0 is not an EOF indicator. Except in some old text file formats (which used 0x1A), there is no EOF indicator present as part of the file. Commented Jul 26, 2018 at 18:10
  • Bytes are bytes. A file is a sequence of bytes. Linux doesn't care. Commented Jul 26, 2018 at 20:20
  • If the zero sequences are very long (thousands of consecutive zeros), you could save disk space by not writing them. (I mean, use e.g fwrite() to write the data up to the start of the (next) sequence of zeros, then use fseek(handle, N*sizeof (int), SEEK_CUR) to "write" N zeros, assuming this is a new file, not overwriting old file data). When read, the unwritten data will read as zeros, exactly as if you had written the zeros. Such files are called "sparse", and are relatively common in Linux, Unix, and POSIXy systems. Commented Jul 28, 2018 at 7:35

1 Answer 1

2

Null bytes in a file don't trigger EOF, even on text files. Hitting EOF is something the I/O libraries are able to detect regardless of content.

As long as you use write or fwrite to write the memory block to disk and later use read or fread to read it, you should be fine.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.