• Advertisement

#### Archived

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

# Just reading in that darn file :p

This topic is 5915 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

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 #include #include 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

##### Share on other sites
Advertisement
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 filenamechar 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

##### Share on other sites
You could also simply: "filename = new char[MAX_PATH];" before reading in the filename, and deleting the memory afterwards.

Z.

Thanks

#### Share this post

##### Share on other sites

• Advertisement
• Advertisement
• ### Popular Tags

• Advertisement
• ### Popular Now

• 10
• 11
• 11
• 11
• 9
• Advertisement