unformatted input to a std::string instead of c-string from binary file.
- by posop
ok i have this program working using c-strings. I am wondering if it is possible to read in blocks of unformatted text to a std::string? I toyed arround with if >> but this reads in line by line. I've been breaking my code and banging my head against the wall trying to use std::string, so I thought it was time to enlist the experts. Here's a working program you need to supply a file "a.txt" with some content to make it run.
i tried to fool around with:
in.read (const_cast<char *>(memblock.c_str()), read_size);
but it was acting odd. I had to do std::cout << memblock.c_str() to get it to print. and memblock.clear() did not clear out the string.
anyway, if you can think of a way to use STL I would greatly appreciate it.
Here's my program using c-strings
// What this program does now: copies a file to a new location byte by byte
// What this program is going to do: get small blocks of a file and encrypt them
#include <fstream>
#include <iostream>
#include <string>
int main (int argc, char * argv[])
{
int read_size = 16;
int infile_size;
std::ifstream in;
std::ofstream out;
char * memblock;
int completed = 0;
memblock = new char [read_size];
in.open ("a.txt", std::ios::in | std::ios::binary | std::ios::ate);
if (in.is_open())
infile_size = in.tellg();
out.open("b.txt", std::ios::out | std::ios::trunc | std::ios::binary);
in.seekg (0, std::ios::beg);// get to beginning of file
while(!in.eof())
{
completed = completed + read_size;
if(completed < infile_size)
{
in.read (memblock, read_size);
out.write (memblock, read_size);
} // end if
else // last run
{
delete[] memblock;
memblock = new char [infile_size % read_size];
in.read (memblock, infile_size % read_size + 1);
out.write (memblock, infile_size % read_size );
} // end else
} // end while
} // main
if you see anything that would make this code better please feel free to let me know.