Archived

This topic is now archived and is closed to further replies.

Destroyer

Just reading in that darn file :p

Recommended Posts

Hi, This is a very quick question. The source is shown below. My questions is why is it when I call fopen - it all goes to hell? If I comment out the whole asking for a filename part then specify a filename myself in fopen - e.g. fopen("Mybmp.bmp, "rb"); It works perfectly fine, just when I try to type it into the program on runtime it screws up as soon as it tries to open the file - any ideas ?
  
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
	char *filename = NULL;
	FILE *file;
	
	short type, bpp;
	long size, width, height;

	cout << "Please type in the name of the bitmap to be read:\n\n";
	cin >> filename;
	
	file = fopen(filename, "rb");

	fread(&type, sizeof(short), 1, file);
	fread(&size, sizeof(long), 1, file);
	fseek(file, 12, SEEK_CUR);
	fread(&width, sizeof(long), 1, file);
	fread(&height, sizeof(long), 1, file);
	fseek(file, 2, SEEK_CUR);
	fread(&bpp, sizeof(short), 1, file);


	if(type != 0x4d42)
	{
		cout << "Not a valid bitmap file!\n\n";
		return 0;
	}
	
	cout << "The size of the bitmap is: " << size << " in bytes\n";
	cout << "The width of the bitmap is: " << width << " in pixels\n";
	cout << "The height of the bitmap is: " << height << " in pixels\n";
	cout << "The bits per pixel in this bitmap is: " << bpp << ''\n'';

	return 0;
}
  

Share this post


Link to post
Share on other sites
Your filename variable doesn''t have enough memory to hold the name entered. Two solutions exist:

// 1. declare the buffer large enough to hold the filename
char filename[MAX_PATH];
...


// 2. Use STL string:
#include <string>
...
string filename;
...
cin >> filename;
...
file = fopen(filename.c_str(), "r");

While we''re on the topic of the STL, you might also want to use file streams:

#include <ftsream>
...
string filename;
fstream file;
...
file.open(filename.c_str(), ios::in|ios::nocreate);
if(file.fail())
{
cout << "Could not open file " << filename << endl;
return -1;
}
// read using stream operations >>, get(), getc(), getline()
// write using <<, put(), putc().




I wanna work for Microsoft!

Share this post


Link to post
Share on other sites