Copying a file multiple times using loop; C/C++
I wanted to copy a file multiple times using different names.
The prog开发者_JAVA技巧ram is this:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include <sstream>
#include<cstring>
using namespace std;
main()
{
string text;
int i;
char ch;
ostringstream oss;
FILE *fp1,*fp2;
if((fp1=fopen("One Dollar.jpg", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
for(i=1; i<=5; i++)
{
oss << "C:\\5241 Dollar\\One Dollar " << i << ".jpg";
text = oss.str();
if((fp2=fopen(text.c_str(), "wb"))==NULL)
{
cout<<"Error "<<i;
exit(-1);
}
while(!feof(fp1))
{
fread(&ch, 1, 1, fp1);
fwrite(&ch, 1, 1, fp2);
}
fclose(fp2);
/* for(int j=0;j<30000;j++)
for(int k=0;k<30000;k++)
if(k==3000)
cout<<k; */
}
fclose(fp1);
}
In this there are two file streams one of which is source and the other is destination.. I loaded the actual file in binary read mode and the destination as binary write mode. I used a for loop to do the work. But as soon as the loop iterates 2nd time, the file opening of fp2 fails. I'm getting the output: Error 2.
How can I make the code work?
You should open and close the first file in each iteration of the loop.
....
for(i=1; i<=5; i++)
{
if((fp1=fopen("One Dollar.jpg", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
....
The reason is because at the end of the first iteration, the first file pointer is at the end of the file, so it won't see any data at the second iteration. You have to close and reopen the file (OR you can use seek
to jump to the front of the file, but this is the simpler change since its a copy-and-paste)
EDIT: to the new question:
you need to reset the stringstream. In the second iteration you are trying to open
C:\\5241 Dollar\\One Dollar 1.jpgC:\\5241 Dollar\\One Dollar 2.jpg
which is invalid.
One solution is to bring the ostringstream declaration into the loop:
....
for(i=1; i<=5; i++)
{
if((fp1=fopen("One Dollar.jpg", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
ostringstream oss;
oss << "C:\\5241 Dollar\\One Dollar " << i << ".jpg";
int main()
{
string text;
int i;
char ch;
ostringstream oss;
FILE *fp1,*fp2;
if((fp1=fopen("/home/maru/fact.cpp", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
for(i=1; i<=5; i++)
{
oss << "/home/maru/fact" << i << ".cpp";
text = oss.str();
rewind(fp1);
cout<<text<<"\n";
if((fp2=fopen(text.c_str(), "wb"))==NULL)
{
cout<<"Error "<<i;
exit(-1);
}
while(!feof(fp1))
{
fread(&ch, 1, 1, fp1);
fwrite(&ch, 1, 1, fp2);
}
fclose(fp2);
oss.str("");
}
fclose(fp1);
return 0;
}
精彩评论