Southperry.net
What's wrong with this code? - Printable Version

+- Southperry.net (https://www.southperry.net)
+-- Forum: Social (https://www.southperry.net/forumdisplay.php?fid=14)
+--- Forum: Rubik's Cube (https://www.southperry.net/forumdisplay.php?fid=58)
+--- Thread: What's wrong with this code? (/showthread.php?tid=17592)



What's wrong with this code? - Fiel - 2009-10-14

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?


What's wrong with this code? - Orit - 2009-10-14

C has no exceptions.
Please add the following after fopen:
Code:
if (foo <= 0)
  perror("fopen failed");



What's wrong with this code? - Fiel - 2009-10-14

This program is just to illustrate a point, not to bother with exception handling.

Windows generates the exception.


What's wrong with this code? - Orit - 2009-10-14

I know, but the exception could happen if the fopen failed. Are you quite sure it succeeded?


What's wrong with this code? - Fiel - 2009-10-14

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.


What's wrong with this code? - Orit - 2009-10-14

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.


What's wrong with this code? - Tempus - 2009-10-14

I can recreate the error, but only when fopen() fails. If the file exists and opens correctly, I don't get any runtime exception.