flirt4fun_143@hotmail.com (sachin bond) wrote in message news:<bjsedi$uo_002@hotmail.com>...[color=blue]
> The following code(in c++) is supposed to divide a file into 'n' different
> files.
>
> suppose i'm having a file called "input.zip".
>
> The execution of the following code should divide "input.zip" into 'n'(user
> specified) different files.
>
> However the code currently..though makes 'n' different files... the divided
> contents are stored only in the first of the 'n' files.
>
> That is.. if "input.zip" has 25kb size, and if i want to divide it into 5
> different files... then,
> actually i should have 5 files with 5 kb each. but this code only gives me 1
> file with 5 kb and the rest 4 files are all 0kb.
>
>
>
> please help me.. with this problem.
>
>
>
> void breaker()
> {
>
>
> long int temppos = 0,pos = 0;
> int n = 0;
> char choice =' ';
> char file[20] = "input.zip";
> char filename[2][30];
>
>
> strcpy(filename[0],file);
> strcpy(filename[1],filename[0]);
> strcat(filename[1],"1");
>
> ifstream infile(filename[0],ios::binary);
>
>
> infile.seekg(0,ios::end);
> pos=infile.tellg();
>
> do
> {
> cout<<" file size in kb : "<<(float)pos/1024;
> cout<<"\nenter number files to be broken into: ";
> cin>>n;
> temppos=pos/n;
> cout<<temppos<<"\n do you want to continue?..press q to re-enter number of
> files..or any other key to continue..";
> cin.get(choice);
>
> }while(choice=='q');
>
> int ctr=0;
>
>
> ofstream outfile(filename[1],ios::binary);
>
> infile.seekg(0,ios::beg);
>
> char byte;
>
> infile.read(&byte,sizeof byte); //read and write functions used for working
>
>
> on data the "binary" way.
>
> char ext='1';[/color]
should be char ext[]="1"; see below why.
[color=blue]
>
> for(int i=0;i<n;i++)
> {
> ext++;
>
>
>
> ctr=0;
>
> while(ctr<temppos) //temppos = pos/n..in line 31
> {
>
>
> outfile.write(&byte, sizeof byte);
>
>
> infile.read(&byte, sizeof byte);
>
> ctr++;
> }
>
> outfile.close();
> strcpy(filename[1],filename[0]);
> strcat(filename[1],&ext);[/color]
This expects to get a 0 terminated string. Above I made ext one so
this now goes ok if you change &ext to ext.
[color=blue]
> outfile.open(filename[1],ios::binary);//this line was the culprit..
> }
>
>
>
> outfile.close();
> infile.close();
>
>
> }[/color]
Why do you open and close your outfile ousite the loop? You can do
something like the following pseudo-code
for(int i=0;i<numfilesiwanttocreate;++i)
{ openoutfilenumber(i);
writetothisfile();
closethefile();
}
This will spare you some lines of code, is much clearer and will not
create a useless extra empty file input.zip3 if you wanted to split
into two files. Alse why not use std::string?
Have a nice day,
Chris Dams