writing beyond EOF and uninitialized bytes

P

pillbug

Hello, I would like to know what the standard says regarding
writing beyond the end of file. For example, in the following
program, is the result always the same or is it system dependent?

#include <cstdio>

int main (int argc, char** argv)
{
char ch = 'A';
FILE* fh = NULL;

// write second byte of file
fh = std::fopen ("data.bin", "w+b");
std::fseek (fh, 1, SEEK_SET);
std::fwrite (&ch, 1, 1, fh);
std::fclose (fh);

// read first byte of file
fh = std::fopen ("data.bin", "rb");
std::fread (&ch, 1, 1, fh);
std::fclose (fh);

if (ch == 0)
std::puts ("zero-initialized\n");
else
std::printf ("uninitialized: 0x%02X\n", (int) ch);

return 0;
}

I apologize for the lack of iostreams.
 
F

Fei Liu

pillbug said:
Hello, I would like to know what the standard says regarding
writing beyond the end of file. For example, in the following
program, is the result always the same or is it system dependent?

#include <cstdio>

int main (int argc, char** argv)
{
char ch = 'A';
FILE* fh = NULL;

// write second byte of file
fh = std::fopen ("data.bin", "w+b");
std::fseek (fh, 1, SEEK_SET);
std::fwrite (&ch, 1, 1, fh);
std::fclose (fh);

// read first byte of file
fh = std::fopen ("data.bin", "rb");
std::fread (&ch, 1, 1, fh);
std::fclose (fh);

if (ch == 0)
std::puts ("zero-initialized\n");
else
std::printf ("uninitialized: 0x%02X\n", (int) ch);

return 0;
}

I apologize for the lack of iostreams.

Try it on different platforms and see it for youself. You could
propbably assume constant behavior.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top