Both of these create a 256 byte file:
#include <fstream>
#include <string>
int main(void)
{
std::ofstream file("output.txt", std::ios_base::binary);
std::string fileString;
for(int i = 0; i < 256; i++)
{
fileString += static_cast<char>(i);
}
file << fileString;
}
And:
#include <fstream>
#include <string>
int main(void)
{
std::ofstream file("output.txt", std::ios_base::binary);
std::string fileString;
for (int i = 0; i < 256; ++i)
{
file << static_cast<char>(i);
}
file.close();
}
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:
#include <cstring>
#include <iostream>
#include <string>
int main(void)
{
std::string result;
result = "apple";
result += static_cast<char>(0);
result += "pear";
std::cout << result.size() << " vs "
<< std::strlen(result.c_str()) << std::endl;
}
Will print two different lengths: one that is counted, one that is null-terminated.