check if a file is already open

This is a discussion on check if a file is already open within the C Programming forums, part of the General Programming Boards category; I'm trying to write a recursive function to read some data from a file that -should- be preformated etc.. well ...

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

    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
    Location
    The edge of the known universe
    Posts
    32,821
    The easiest and cleanest way would be something like a wrapper function to open the file.
    Code:
    void wrapper ( char *filename ) {
      FILE *fp = fopen(filename,"r");
      recursive(fp);
      fclose(fp);
    }
    This is fugly
    Code:
    void recursive ( char *filename ) {
      static FILE *fp = NULL;
      if ( !fp ) {
        fp = fopen(filename,"r");
        // read from static fp
        recursive(filename);
        fclose(fp);
        fp = NULL;
      } else {
        // read from static fp
        recursive(filename);
      }
    }
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

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, 03: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

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