Notices
Results 1 to 4 of 4

Thread: Why is it necessary to use fclose() after fopen() in C?

  1. #1 Why is it necessary to use fclose() after fopen() in C? 
    Forum Freshman
    Join Date
    Nov 2009
    Posts
    9
    I was wondering what the exact reason was for having to use fclose() after using fopen() in C. Thanks


    Reply With Quote  
     

  2.  
     

  3. #2  
    Forum Sophomore
    Join Date
    Mar 2009
    Posts
    139
    If you do not close a file after you are done reading it, it may become corrupt when the process ends, or just plain inaccessible.

    If you put fclose before fopen, there is nothing to close.

    I think this covers both possibilities of what you might be asking, if not, clarify please.


    --
    -M

    "Those that would give up essential liberty to obtain a little temporary
    safety deserve neither liberty nor safety."

    -Benjamin Franklin, An Historical Review of Pennsilvanya, 1759
    Reply With Quote  
     

  4. #3  
    Forum Freshman
    Join Date
    Nov 2009
    Posts
    9
    The first one covered my question. I was just wondering what would happen if you did not close it. I do apologize though about my question being so vague. Thank you for your time
    Reply With Quote  
     

  5. #4 fopen and fclose 
    Forum Freshman
    Join Date
    Feb 2009
    Location
    Yangon
    Posts
    9
    If you have studied Database Management System, I think it is very clearly defined. I am a java developer but I hope it can help you. First of all, I will explain fopen, but it may be right.

    fopen()
    I will give you an example. You are drawing a picture on a paper. When you drawing, your younger brother get your paper and erase all of them. What would you do? But you can prevent from your brother for getting your paper.
    As the same way, fopen() set the lock (X lock in DBMS) on your file. It prevent others from accessing your file that you wrote until it has been finished. So, nobody can access your text or file while you are writing.

    fclose
    Same as before. If you don't put fclose after you finish writing file, do data is reached. In java, no data is reached if you don't run close().Other hand, I think this may give a hang to your program when you access next time again. I also think it may even cause a security hole to your system.

    why we must use fclose() after using fopen()
    we use fopen() for setting lock to the file from accessing and fclose() is for accomplish we have finished writing, no access is later required, release locks and stop access to this file. (same as COMMIT in DBMS).

    I think it may help you.
    Reply With Quote  
     

Bookmarks
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
  •