Sign in to follow this  

[C++] Outputting Binary from an Image

This topic is 4815 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to write a console C++ program that when executed, gets reads an image from a file, and then outputs the HTTP headers for it, and the image data. This will be executed by the web server and act as a CGI script. I managed to read the file into a char array from an ifstream, and I know it's valid because I can write it back out to an ofstream to make a copy of the file. But I need it to output to the file to the "console" so that the web server can read it. Doing it with printf, fwrite, and cout all change the data, corrupting the image. I've searched all through the net, but I'm stumped. Help me GameDev Kenobi. You're my only hope.
	struct stat results;

	char *buffer=new char[MAXIMAGESIZE];
    
	if (stat("image.jpg", &results))
		return 0;

	if (results.st_size>MAXIMAGESIZE)
		return 2;

	ifstream image ("image.jpg", ios::in | ios::binary);
	
	if(!image.read(buffer,results.st_size))
		return 3;

	printf("Content-type: image/jpeg\r\n\r\n");

	fwrite(buffer,results.st_size,1,stdout);


	image.close();

Share this post


Link to post
Share on other sites
You know. I search and search and search with Google before I bother posting a question on a forum. But it never fails that after I decide to ask for help, I figure it out before anyone even replies.

I added

_setmode(fileno(stdout), _O_BINARY);

before the call to fwrite() and it solved my problem.

Share this post


Link to post
Share on other sites

This topic is 4815 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this