Thread: Determining the ability to delete a file

  1. #1
    Registered User
    Join Date
    Dec 2002
    Posts
    16

    Cool Determining the ability to delete a file

    I need to be able to determine if I can delete a file in NT/2000/XP, before actually deleteing it. The problem is, other applications may already have an open handle to the file. This causes any attempt to delete the file in an NT based OS to fail.

    The only thing I can think of is to try to rename the file. This should also fail if another process has an open handle to the file. But I would rather not do this for every file since I maybe processing thousands of files.

    Thank you for your time.

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Well, you could start with the file attributes, confirm deletability there, then just rename the file and then back again with something like:

    Code:
    bool deletable(const char f[])
    {
     int attempt = 0;
     const char * tmp = "m_p188jssz";
     char temp[128] = {0}; 
     bool success = false;
       while(++attempt <= 128) 
      {
           if((success = rename(f, temp) != 0)
         {
           rename(temp, f);
           break;
         } 
           else sprintf(temp, "%s%s%s", tmp, attempt, ".txt"); 
      }
     return success;
    }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  3. #3
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,868
    Why do you need to know if you can delete the file before you try?
    Why not try. If fail then work out why and fix.

    Code:
    if(!DeleteFile(sFullFileNameAndPath))//failed to delete
    {
         iError=GetLastError(); there are 100's of defined values for this function
         if(iError==ERROR_FILE_NOT_FOUND)
          //no file
         else if(iError==ERROR_SHARING_VIOLATION)
    
    }
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

  4. #4
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    Because he doesn't want to delete the data at that point! He just wants to know if he CAN delete it.

  5. #5
    Registered User
    Join Date
    Dec 2002
    Posts
    16

    The reason...

    The reason I need to know before I delete is that I need to zero the file out before deleting. If I zero the file out, then try to delete and I can't delete, then I don't want to delete the file. But now the file is already zero'd and worthless.

    I wanted to try to find a way to determine this other than renaming, because the program may be testing thousands of files, and I imagine that to rename thousands of files and rename them back would be a waste of time, especially since the FAT would have to updated on every name change.

  6. #6
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,868
    How about reading data to memory,
    try deleteing it,
    then you can write the data back to the file if needed or fill it with rubbish


    Code:
    hFile=CreateFile(.................);//open existing file
    //error check to see if opened
    iSize=GetFileSize(hFile,NULL);//small files
    //alloc mem this size and error check
    //read file for this size and error check
    //CloseHandle(hFile);
    
    //find if file will delete
    
    
    //free the memory
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

  7. #7
    Registered User
    Join Date
    Dec 2002
    Posts
    16

    Cool

    That would be even slower than renaming the file.

  8. #8
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,868
    OK

    this might help.
    http://msdn.microsoft.com/library/de...ile_object.asp



    >>That would be even slower than renaming the file.<<
    But it would do the whole job and fit into the sequence you outlined. Rather than a seperate test to see if the file would delete / rename.

    Code:
    Open File
    
    Find File Size
    
    Alloc Mem
    
    Read File to mem
    
    Fill File with zeros
    
    if(Delete File == FAIL)
         Rewrite Data
         CloseFile
    
    Free Memory
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

  9. #9
    Registered User dizolve's Avatar
    Join Date
    Dec 2002
    Posts
    68
    I'm sorry but if the file was locked from being deleted (written), wouldn't that also stop you from writing 0's? Why not just try to write it?

    &nbsp;&nbsp;__&nbsp;&nbsp;&nbs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;\/____/&nbsp;\/__/&nbsp;&nbsp;&nbsp;\/____/
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n bsp;&nbsp;I&nbsp;have&nbsp;a&nbsp;BAD&nbsp;figlet& nbsp;addiction.

  10. #10
    Registered User
    Join Date
    Dec 2002
    Posts
    16
    It's not locked in the since that a process has called LockFile(), it's just the file has been opened for reading by another process. In NT/2000/XP, if a file is open by another process already, another process can not delete it.

    The process can write to the file, because the other file only open it for reading.

  11. #11
    fou
    Guest
    I have not tried this but I think it is what you are looking for.
    Code:
    HANDLE hFile;
    
    /* Try to open the file with no sharing rights. This will cause
     * an error if another program has it open. Request access to
     * write to and delete the file. */
    hFile = CreateFile(fileName,GENERIC_WRITE | DELETE,0,NULL,OPEN_EXISTING,0,NULL);
    
    if (hFile == INVALID_HANDLE_VALUE) {
    	if (GetLastError() == ERROR_SHARING_VIOLATION) do something; /* Someone has it open */
    	else do something; /* probable ERROR_FILE_NOT_FOUND or ERROR_ACCESS_DENIED */
    	}
    	else {
    		//do stuff
    		CloseHandle(hFile);
    		//DeleteFile()
    	}
    }
    Check out the doc for CreateFile for possible issues.

  12. #12
    fou
    Guest
    It should also be noted that in the scenario you outline the zeros will probably never hit the harddisk without a call to FlushFileBuffers.

    Trying rename, write, etc to test if a file can be deleted may not work on NTFS as each of these permissions can be set separately.

    In my previous example, there is a miniscule chance that another process could open the file between CloseHandle and DeleteFile. To stop this you may wish to use the FILE_FLAG_DELETE_ON_CLOSE flag in CreateFile and then do a final check that the file is deleted after CloseHandle.

  13. #13
    Registered User
    Join Date
    Dec 2002
    Posts
    16
    I believe that the DELETE flag for CreateFile() is based on user access rights, and not on current file operations. Therefore, the user may have the rights to delete the file, but still would not be able to because it is already opened by another process.

    I will test it anyway and post the result of my test.

  14. #14
    fou
    Guest
    Setting the dwShareMode argument to 0 is what guarantees that your file is not open by another process.
    MSDN:
    You cannot request a sharing mode that conflicts with the access mode specified in a previous open request whose handle is still open.
    0 conflicts with everything.

    Determining security access with the dwDesiredAccess argument at the same time is a bonus.

    For reference, I wrote a sample for using ODBC with excel that required the excel file not be open (if an open excel file is altered bad consequences ensue). This was my function:
    Code:
    BOOL isFileOpen(LPTSTR fileName) {
    
    	/* Check if another program has a file open */
    
    	HANDLE hFile;
    
    	/* Try to open the file with no sharing rights. This will cause
    	 * an error if another program has it open */
    	hFile = CreateFile(fileName,GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);
    
    	if (hFile == INVALID_HANDLE_VALUE) {
    		if (GetLastError() == ERROR_SHARING_VIOLATION) return TRUE; /* Someone has it open */
    		else return FALSE; /* probable ERROR_FILE_NOT_FOUND */
    	}
    	else {
    		CloseHandle(hFile);
    		return FALSE;
    	}
    }
    The sample can be found at:
    http://www.john.findlay1.btinternet....e/database.htm

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  3. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  4. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM