I want to read file in binary mode using fread() into structure members.
following is the code which works perfectly on Turbo C compiler(DOS base) but doesn't work for VC++ 6, it is giving exception at fread() statement.

The input to this file we can give any .bmp file name e.g. abc.bmp

output
header->bfType 19778
.
.
header->bfOffBits 54

//Program Starts here
#include<stdio.h>
#include<conio.h>

typedef unsigned int WORD;
typedef unsigned long DWORD;
typedef unsigned char BYTE;

typedef struct tagBITMAPFILEHEADER {
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} BITMAPFILEHEADER;

char f1[20];
FILE *in;
BITMAPFILEHEADER *header;

void main()
{

printf("\nEnter input file name: ");
scanf("%s",f1);
//printf("\nEnter output file name: ");
//scanf("%s",f2);

/*OPEN INPUT IMAGE FILE(.BMP)*/
if ((in=fopen(f1, "rb")) == NULL)
{
   fprintf(stderr, "Cannot open input file.\n");
      return 1;
      }
      else
      {
      fread(&header->bfType,	sizeof(header->bfType),	1,	in);
      fread(&header->bfSize,	sizeof(header->bfSize),	1,	in);
      fread(&header->bfReserved1,	sizeof(header->bfReserved1),	1,	in);
      fread(&header->bfReserved2,	sizeof(header->bfReserved2),	1,	in);
      fread(&header->bfOffBits,	sizeof(header->bfOffBits),	1,	in);

      printf("\nheader->bfType %u",header->bfType);
      printf("\nheader->bfSize %ld",header->bfSize);
      printf("\nheader->bfReserved1 %u",header->bfReserved1);
      printf("\nheader->bfReserved2 %u",header->bfReserved2);
      printf("\nheader->bfOffBits %ld",header->bfOffBits);
      }
      getch();


      }

Recommended Answers

All 2 Replies

If it worked in Turbo C it was because you were lucky. header is an unallocated pointer. Since it is in global space the pointer's value is initialized to 0 during the program's startup code, which is executed before main() is called.

The program crashes because you need to call malloc() to allocate memory to that pointer before calling fread()

it worked in Turbo C, because Turbo C is riddled with undefined behavior and non-ANSI libraries in standard distribution. It's the AOL of C compilers. In other words, it's a joke. Do yourself a huge favor and quit using it.

anyhow.... if you're intent on keeping "header" declared as pointer, then do exactly what Dragon said. Personally, I don't see why you need it to be a pointer since it's local to main. You could more easily declare "header" directly, and write it without all the pointer mechanisms and memory allocations (which has its own additional dangers).

but either way

.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.