Reputation: 64
I read a text file and it works very well.
std::string str_buf = "";
FILE *file = fopen("/home/pi/log_2019-03-07.txt", "r");
if (file != NULL)
{
while (true)
{
char buffer[MAX_BUFFER_SIZE] = { 0x00, };
size_t rSize = fread(buffer, MAX_BUFFER_SIZE, sizeof(char), file);
str_buf += buffer;
if (rSize == 0)
break;
}
printf("%s", str_buf.data());
fclose(file);
}
Then I try to write it to same path, another name. This is the code:
FILE *writefile = fopen("/home/pi/WriteTest.txt", "wb");
if (writefile != NULL)
{
int offset = 0;
while (true)
{
size_t wSize = fwrite(&str_buf.data()[offset], sizeof(char), strlen(str_buf.data()) - 1, writefile);
offset += (int)wSize;
if (offset >= strlen(str_buf.data()))
break;
}
fclose(writefile);
}
If I try to execute this code, it works. I open WriteTest.txt
, it has same string. It's perfectly same.
But I found WriteTest.txt
's volume is almost 2 twice read text.
Why it happens?
Upvotes: 0
Views: 201
Reputation: 8475
size_t wSize = fwrite(&str_buf.data()[offset], sizeof(char), strlen(str_buf.data()) - 1, writefile);
you start writing the text at offset &str_buf.data()[offset]
but you write the length of a string starting at position 0. You are writing offset
bytes too much. You should
size_t wSize = fwrite(&str_buf.data()[offset], sizeof(char),
strlen(str_buf.data()) - offset, writefile);
Also, you don't write string length nor a NUL terminator. So you'd have trouble figuring out how much to read unless, like in your simple example, it is at file's end.
And last, it's better to use str_buf.length()
rather than strlen. It's faster and works with strings that have NUL in the middle.
Upvotes: 1