Thread: check if a file is already open

  1. #1
    Registered User Destinps's Avatar
    Join Date
    Oct 2012
    San Antonio, Texas, United States

    check if a file is already open

    I'm trying to write a recursive function to read some data from a file that -should- be preformated etc..

    well the function call only takes a file name, so I'm opening the file within the function as well.

    Is there a way, when i call the function from within the function, to do a check that I already opened the file and skip opening it again?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    The easiest and cleanest way would be something like a wrapper function to open the file.
    void wrapper ( char *filename ) {
      FILE *fp = fopen(filename,"r");
    This is fugly
    void recursive ( char *filename ) {
      static FILE *fp = NULL;
      if ( !fp ) {
        fp = fopen(filename,"r");
        // read from static fp
        fp = NULL;
      } else {
        // read from static fp
    Finding out whether the file is open would involve expensive OS calls (and be very non-portable).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 03-08-2010, 02:43 PM
  2. Open File/Save File crashes on cancel?
    By Blackroot in forum Windows Programming
    Replies: 0
    Last Post: 08-02-2008, 02:16 AM
  3. Check For Open Programs
    By mikeman118 in forum Windows Programming
    Replies: 22
    Last Post: 02-27-2008, 07:12 PM
  4. Replies: 12
    Last Post: 03-10-2005, 07:48 PM