Segmentation fault by fopen(file,"r")

This is a discussion on Segmentation fault by fopen(file,"r") within the C Programming forums, part of the General Programming Boards category; Hallo, i have an Segmentation fault notice while running following script : Code: #include <stdio.h> main() { char datei[] = ...

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    2

    Segmentation fault by fopen(file,"r")

    Hallo,

    i have an Segmentation fault notice while running following script :
    Code:
     
    #include <stdio.h>
    
    main() {
    
        char datei[]  = "./checksum";
    
        FILE *fp;
    
        fp = fopen(datei,"r");
        
        if(fp == NULL) {
    
            printf("dont exists\n");
    
        }
        else {
            printf("exists\n");
        }
        fclose(fp);
    
    }
    I'm sure that the line fp = fopen(datei,"r"); produces the error. If i change the line to fp = fopen(datei,"w"); the error "Segmentation fault" dont happen.

    Please so kind and help me, please.

    Regards,

    Stefan

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    Even if fp is NULL you still call fclose on it. Do you have permision to read from the file?

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Put the fclose() call inside the else.

    fclose(NULL) causes a segmentation fault.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    Registered User
    Join Date
    Feb 2006
    Posts
    2

    Thanks

    I had to set the fclose() function into die else clause.

    Lots of thanks!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why am I getting segmentation fault on this?
    By arya6000 in forum C++ Programming
    Replies: 6
    Last Post: 10-12-2008, 07:32 AM
  2. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 06:04 PM
  3. Segmentation fault
    By NoUse in forum C Programming
    Replies: 4
    Last Post: 03-26-2005, 03:29 PM
  4. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 01:33 PM
  5. Segmentation fault...
    By alvifarooq in forum C++ Programming
    Replies: 14
    Last Post: 09-26-2004, 01:53 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21