Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What's wrong with this code?
#1
Code:
#include <stdio.h>

struct myStruct
{
  int a;
  int b;
};

int main(void)
{
  FILE* foo;
  struct myStruct bar;

  foo = fopen("foobar.txt", "rb");
  fread(&bar.a, 4, 1, foo);
  fclose(foo);
  printf("%d\n", bar.a);

  return 0;
}

The program generates a runtime exception when executing the fread() command. What's the correct way to do this?
Reply
#2
C has no exceptions.
Please add the following after fopen:
Code:
if (foo <= 0)
  perror("fopen failed");
Reply
#3
This program is just to illustrate a point, not to bother with exception handling.

Windows generates the exception.
Reply
#4
I know, but the exception could happen if the fopen failed. Are you quite sure it succeeded?
Reply
#5
Ah, I see what you're saying. My bad.

Yes, I'm 100% sure it succeeded. I use a function "safe_fopen" which always checks for NULL when opening a file.
Reply
#6
Are the arguments to fread correct?
ISTR all the "f" family of functions having the FILE* as first argument, but I shamefully admit I have no C compiler on this, my mapling machine, so I can't make sure.
Reply
#7
I can recreate the error, but only when fopen() fails. If the file exists and opens correctly, I don't get any runtime exception.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)