开发者

Segmentation fault while using ferror() in a simple program. Why?

Why is the following code giving segmentation fault?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *file;
    file = fopen("text","r");
    if (file == NULL) printf("Error READING FILE");
    if (ferror(file)) printf("error reading file");    //line 9
    return 0;
}

Doing backtrace in gdb gives:-

> #0  开发者_开发百科0x00007ffff7ad9d30 in ferror () from /lib/libc.so.6
> #1  0x00000000004005fa in main () at test.c:9


file is NULL. You're not seeing the first printf because the program crashes before stdout is flushed.


If fopen returns NULL, then the file isn't open; you're passing NULL in to ferror, which is invalid. You don't have an open file to pass in; that's what NULL means, that it couldn't give you a file pointer. ferror is for getting errors related to reading and writing the file, once it has actually been opened and you have the file to work with.

If fopen fails, and you want to get more information about why, you need to check the errno global variable, defined in errno.h.

#include <errno.h>

// ...snip...

if (file == NULL) 
  printf("Error READING FILE: %s\n", strerror(errno));

This example shows how to fetch a string describing the error; you could also compare the value in errno against one of the possible values it could have, and do something different depending on what the error is. See the fopen man page, or the POSIX spec, for a list of possible errors to compare against. Here's how you could check against various possible errors:

if (file == NULL) {
  int error = errno;  // copy it so other calls like printf don't modify it
  printf("Error READING FILE: %s\n", strerror(error));
  switch (error) {
  case EACCESS:
    // access was denied
    break;
  case ENOENT:
    // the file or one of its ancestors doesn't exist
    break;
    // etc...
  }
}

(this is an expansion of something I originally wrote in a comment on another answer)


If file is equal to NULL on line 9, then the Seg Fault will occur during the ferror() call.

If there the file is NULL (as determined on line 8), then you shouldn't perform line 9.

Your line 8 code should be changed as such:

if (file == NULL)
{
    printf("Error READING FILE");
    return 1;
}

NB: i could be very wrong about this, it's been a while since i've done C/C++

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜