Results 1 to 7 of 7
  1. Default What's wrong with this code?


    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?

  2. Default


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

  3. Default


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

    Windows generates the exception.

  4. Default


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

  5. Default


    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.

  6. Default


    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.

  7. Default


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

  8.  

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •