I'm writing a small Win32 Console app that manipulates the contents of binary files. It accepts the filename as a command line parameter and writes to a file named filename.scramble
This is the first time I'm dynamically allocating memory for C strings (which I'm using since the fstream functions use const char*).
The code is as follows. I've added the comments to help you understand what I'm trying to do. Please tell me whether I'm doing anything unsafe with pointers or whether I'm allocating memory wrong or any unsafe practice you see regarding dynamically allocating and concatenating C strings in C++. My question is specifically about the strings and the memory management.
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc, char *argv[])
{
//Program needs at least one extra argument
//If less, print 'usage'
if (argc < 2)
cout<<"usage: "<< argv[0] <<" <filename>\n";
else
{
//Assuming argv[1] is a file name
fstream fin (argv[1],ios::binary|ios::in);
if (!fin.is_open())
cout<<"Could not open file\n";
else
{
//Calculate size of file
fin.seekg(0,ios::end);
unsigned long long size = fin.tellg();
//Find out how many left over characters
//if using blocks of 16 characters
int lastset=size%16;
//Change size to number of blocks
size /= 16;
//File name must be <original filename>.scramble
//Allocate space
char* name = new char[sizeof(argv[1])+8];
//Concatenate <original filename>
strcat_s(name,sizeof(argv[1]),argv[1]);
//Concatenate ".scramble"
strcat_s(name,sizeof(argv[1])+8,".scramble");
fstream fout (name,ios::binary|ios::out);
//Buffer
char memblock[16];
fin.seekg(0,ios::beg);
//Read from fin and write to fout in blocks of 16 characters
for(unsigned long long i=0;i<size;++i)
{
fin.read(memblock,16);
/*
*
* Manipulation on memblock to be done here
*
*/
fout.write(memblock,16);
}
//No manipulation for last n bytes, n<16
fin.read(memblock,lastset);
fout.write(memblock,lastset);
fin.close();
fout.close();
delete[] name;
}
}
return 0;
}
std::string name(argv[1] + std::string(".scramble"));
– William Morris Mar 9 '13 at 2:52