ofstream::put() writes 2 bytes instead of 1?!
-
I'm trying to create a function which just creates a file and fills it with random bytes. I want to be able to specify the size. I do this like this...
bool CreateRandomFile(const char* pszDest, unsigned int nLen)
{
if (!nLen) return false;
static const nByteSize = sizeof(byte) * 256;
ofstream fDest(pszDest);
if (!fDest) return false;
for (int i = 0; i < nLen; i++)
fDest.put(byte(::rand() % nByteSize));
fDest.close();
return true;
}This doesn't work because when (::rand() % nByteSize) becomes 10, 2 bytes are written instead of just the one. The 2 bytes are the standard "\r\n" thing and I guess it's supposed to be this way. But what should I do to get it to work properly? byte is typedef'ed like this:
typedef unsigned char byte;
And btw.: fDest.put(10) writes 2 bytes too, and fDest.put(9) writes 1. I'm using the header "fstream" and namespace std. Sprudling :confused:
-
I'm trying to create a function which just creates a file and fills it with random bytes. I want to be able to specify the size. I do this like this...
bool CreateRandomFile(const char* pszDest, unsigned int nLen)
{
if (!nLen) return false;
static const nByteSize = sizeof(byte) * 256;
ofstream fDest(pszDest);
if (!fDest) return false;
for (int i = 0; i < nLen; i++)
fDest.put(byte(::rand() % nByteSize));
fDest.close();
return true;
}This doesn't work because when (::rand() % nByteSize) becomes 10, 2 bytes are written instead of just the one. The 2 bytes are the standard "\r\n" thing and I guess it's supposed to be this way. But what should I do to get it to work properly? byte is typedef'ed like this:
typedef unsigned char byte;
And btw.: fDest.put(10) writes 2 bytes too, and fDest.put(9) writes 1. I'm using the header "fstream" and namespace std. Sprudling :confused:
Open the file in binary mode. Joaquín M López Muñoz Telefónica, Investigación y Desarrollo