C++ writing string to file = extra bytes
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.
f开发者_运维百科or(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:
#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.
im not too gud with c++ but did you try initializing the filestring variable with null or '/0' ?? Maybe then it will give 256byte file..
N yea loop should be < 256
PS: im really not sure but then i guess its worth trying..
精彩评论