Click here to Skip to main content
14,827,050 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to copy - write an image using C++ fstream functions (without using any standard commands for copying files using C++).

Below is the code i wrote :

void main()
{
	char *imgs=NULL;
	imgs = new char[filsz()];
	ifstream inm("aaa.jpg",ios::in|ios::binary);
	for(int i=0;i<filsz();i++)
	{
		inm>>imgs[i];
	}
	ofstream outnm("linm.jpg",ios::out|ios::binary);
	for(int i=0;i<filsz();i++)
	{
		outnm.put(imgs[i]);
	}
	
	
	
}

long filsz()
{
	fstream inm("aaa.jpg",ios::in);
	inm.seekg(ios::beg,ios::end);
	long sz = inm.tellg();
	return sz;
	
}
</pre>



The file size of the input and output file was the same , i could open the original file with windows image viewer however when it comes to copied file it wont open and shows an error.

What could be the reason ?
Posted

The first thing I would do, is to change from char to unsigned char in case it is "losing" the top bit, and try caching the file size to save waste: you are calling the filsz function for each and every byte in the file, twice, as it is called each time the for loop needs to see if it should go round again:
C++
int bytes = filsz();
imgs = new unsigned char[bytes];
ifstream inm("aaa.jpg",ios::in|ios::binary);
for(int i=0; i < bytes; i++)


If that doesn't sort it, then you need to look at the actual data in the file(s) to work out what is being output for what input. PsPad[^] has a HEX mode which would make that relatively simple (and it's not a bad editor, either if you need more complex editing than VS can provide - I don't use it much, but it can save a lot of time)

[edit]Stupid HTML... - OriginalGriff[/edit]
   
v2
Comments
compuknow 11-May-13 5:19am
   
Changing it unsigned doesn't work , as suspected all the data in the input file does not match with those on the output file.

Is there any way to absorb image data from the image in hexadecimal matrix (array) format and then output it as a new image file.
I see that you haven't closed any of the two files. While its okay when you are reading the file, after writing all the data to the file, close it with a simple

outnm.close();

after the write loop.

This will flush all the contents in the file that the system usually caches
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900