I am using c++ to look through 256 counts and write the ASCII representative to a file.
If i use the method of generating a 256 character string then write that string to the file, the file weighs 258bytes.
string fileString = "";
//using the counter to attach the ASCII count to the string.
for(int i = 0; i <= 256; i++)
{
fileString += i;
}
file << fileString;
If i use the method of writing to the file withing the loop, the file is exactly 256bytes.
//using the counter to attach the ASCII count to the string.
for(int i = 0; i <= 256; i++)
{
file << (char)i;
}
Whats going here with the string, what extra information from the string is being written to the file?
Both of these create a 256 byte file:
And:
Note, before you had an off-by-one error, as there is no 256th ASCII character, only 0-255. It will truncate to a char when printed. Also, prefer
static_cast.If you do not open them as binary, it will append a newline to the end. My standard-ess is weak in the field of outputs, but I do know text files are suppose to always have a newline at the end, and it is inserting this for you. I think this is implementation defined, as so far all I can find in the standard is that “the destructor can perform additional implementation-defined operations.”
Opening as binary, of course, removes all bars and let’s you control every detail of the file.
Concerning Alterlife’s concern, you can store 0 in a string, but C-style strings are terminated by 0. Hence:
Will print two different lengths: one that is counted, one that is null-terminated.