Thread: C Delete opened file

  1. #1
    Registered User
    Join Date
    Dec 2008
    Posts
    6

    C Delete opened file

    Hi,

    I am in the early stages of learning C (previously coded in java, PHP etc.).

    The code below is a simple menu which enables you to:
    create, delete, open and close a file.

    The problem i have is if you choose to create the file, then open it, it is then not possible to delete it (gives error 32).
    If you delete without opening it works fine or if you restart the program and then delete the file that was created in the last run it is also ok. Just seems you cant create, open and delete in same operation.

    Any input would be helpful.

    Code:
    // for Win Xp Pro
    #define _WIN32_WINNT 0x0501
    #include <windows.h>
    #include <stdio.h>
    
    int main()
    {
      HANDLE hFile;
      char fname[30] = "C:\\testfile.txt";
      int menuOption;
    
    do {
          printf("\n");
          printf("0) Exit\n");
          printf("1) Close File\n");
          printf("2) Delete File\n");
          printf("3) Create File\n");
          printf("4) Open File\n");
          scanf("%d", &menuOption);
    
        switch(menuOption)
        {
            case 0 :
                break;
            case 1 :
                //close option
                if(CloseHandle(hFile) != 0)
                  printf("CloseHandle() succeeded!\n");
                else printf("CloseHandle() failed!\n");
                break;
            case 2 :
                //delete option
                if(CloseHandle(hFile) != 0)
                  printf("CloseHandle() succeeded!\n");
                else printf("%s could not be closed! error %u\n", fname, GetLastError());
    
                if(DeleteFile(fname) != 0)
                  printf("%s file successfully deleted!\n", fname);
                else printf("%s could not be deleted! error %u\n", fname, GetLastError());
                break;
            case 3 :
                //create option
                hFile = CreateFile(fname,               // file to be opened
                                    GENERIC_WRITE,      // open for writing
                                    FILE_SHARE_WRITE,   // share for writing
                                    NULL,               // default security
                                    CREATE_NEW,         // create new file only
                                    FILE_ATTRIBUTE_NORMAL |FILE_ATTRIBUTE_ARCHIVE | SECURITY_IMPERSONATION,
                                                        // normal file archive and impersonate client
                                    NULL);              // no attribute template
    
                if(hFile == INVALID_HANDLE_VALUE)
                  printf("Could not create %s file, error %u.\n", fname, GetLastError());
                else printf("%s file created successfully, error if any, %u.\n", fname, GetLastError());
                break;
            case 4 :
                //open option
                hFile = CreateFile(fname,            // file to create
                          GENERIC_WRITE,             // open for writing
                          FILE_SHARE_WRITE,          // allow write share
                          NULL,                      // default security
                          OPEN_EXISTING,             // opens a file
                          FILE_ATTRIBUTE_NORMAL |FILE_ATTRIBUTE_ARCHIVE | SECURITY_IMPERSONATION,
                          NULL);                     // no attribute template
    
                if(hFile == INVALID_HANDLE_VALUE)
                  printf("Could not open %s file, error %u.\n", fname, GetLastError());
                else printf("%s file opened successfully, error if any, %u.\n", fname, GetLastError());
                break;
            default :
                //error message
                printf("Sorry but %d is not a valid option!", menuOption);
                break;
        }
     } while (menuOption !=0);
    
      return 0;
    }
    Thanks,
    Gid

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    It's all pretty complex with permissions, http://msdn.microsoft.com/en-us/libr...15(VS.85).aspx

    Basically see the "Remarks" section.
    To delete or rename a file, you must have either delete permission on the file, or delete child permission in the parent directory.
    > Just seems you cant create, open and delete in same operation.
    I hope you don't mean create, open then delete... You can't open the same file twice (or at least you might not be able to ).

    Mods: this probably belongs in Windows programming.
    Last edited by zacs7; 12-04-2008 at 06:01 AM.

  3. #3
    Registered User
    Join Date
    Dec 2008
    Posts
    6
    I have tried to give the FILE_SHARE_WRITE | READ | DELETE permissions but that seems to error.

    If you run the above code it allows you to create file, when you then open file you get a success message. delete then fails. (options 3, 4 then 2)

    if instead you just choose (options 3 and 2) it creates successfully and then deletes successfully.

    Note: the above was coded and compiled in code::blocks.

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Of course you cannot delete it after you've opened it. The same applies to any language, because it's enforced by the OS.
    As long as there is an application that has an open handle to the file, you can't delete it.

    And you should probably use fopen/fclose instead of CreateFile. More portable and not so horrible.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    chococoder
    Join Date
    Nov 2004
    Posts
    515
    Quote Originally Posted by Elysia View Post
    Of course you cannot delete it after you've opened it. The same applies to any language, because it's enforced by the OS.
    As long as there is an application that has an open handle to the file, you can't delete it.
    That would of course depend on the operating systems. Some *nix flavours allow some accounts to delete open files for example.
    Handy for truncating logfiles, just delete the file and a well-written server will just create a new one with the same name.

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Error 32 means "Sharing Violation", so you are trying to delete the file whilst it is in use, according to Windows.

    What exact steps are you doing to cause this to happen? It appears to work on my machine with your code - but maybe I'm missing something.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by jwenting View Post
    That would of course depend on the operating systems. Some *nix flavours allow some accounts to delete open files for example.
    Handy for truncating logfiles, just delete the file and a well-written server will just create a new one with the same name.
    Which is just silly to me. That would allow programs to delete or truncate some critical files, which the application is keeping open on purpose to block access to it.
    Sometimes I don't get Linux at all, with all its security & all that.
    If you can write to open files, it can even be a security risk.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by jwenting View Post
    That would of course depend on the operating systems. Some *nix flavours allow some accounts to delete open files for example.
    Handy for truncating logfiles, just delete the file and a well-written server will just create a new one with the same name.
    Actually, it continues writing to the existing (now invisible) file until the server is restarted (or until it closes and opens the file for some other reason). And as far as I know, it has nothing to do with what account you have - that will only affect what files you can delete, but not whether you can delete one that is open or not.

    Edit: I'm pretty sure that a file CAN be opened in such a way that it's not allowed to be deleted - but a file opened with standard parameters to "fopen" can certainly be deleted directly by anyone who has permission to delete that file. Of course, lock-files for servers and such are usually opened by root or some other "non-user-accessible" account - so that prevents a random malicious user from deleting the file. If the user has root-access, then nothing is safe, right?

    --
    Mats
    Last edited by matsp; 12-04-2008 at 06:31 AM.
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #9
    Registered User
    Join Date
    Dec 2008
    Posts
    6
    Sorry,

    Just to clarify, the delete procedure performs a close on the handle before attempting the delete.
    This close succeeds but the subsequent delete fails.

    When running this on my system the following options replicate my error.

    Select option 3.
    Select option 4.
    Select option 2.

    I am running WinXP sp2.

    Cheers,
    Gid

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by matsp View Post
    Edit: I'm pretty sure that a file CAN be opened in such a way that it's not allowed to be deleted - but a file opened with standard parameters to "fopen" can certainly be deleted directly by anyone who has permission to delete that file. Of course, lock-files for servers and such are usually opened by root or some other "non-user-accessible" account - so that prevents a random malicious user from deleting the file. If the user has root-access, then nothing is safe, right?
    Is that for Linux, then? Because default parameters for fopen on Windows is exclusive - non-deletable. I don't know if it is possible to delete an open file, but it is possible to allow other processes to read and write to the file at the same time.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User
    Join Date
    Dec 2008
    Posts
    6
    From my limited experience it seems to me that one of the following is happening:

    1) the code used to open the file (switch case 4) is changing the permissions in some way as to restrict deletion.

    2) The code to close the file (switch case 2) that is as follows: if(CloseHandle(hFile) != 0)
    Does not actually close the file like it says.

  12. #12
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    > If you can write to open files, it can even be a security risk.
    That's what flockfile() is for... Bang supposed security risk gone (I can't even see how there would be one anyway...)

  13. #13
    chococoder
    Join Date
    Nov 2004
    Posts
    515
    Quote Originally Posted by matsp View Post
    Actually, it continues writing to the existing (now invisible) file until the server is restarted (or until it closes and opens the file for some other reason). And as far as I know, it has nothing to do with what account you have - that will only affect what files you can delete, but not whether you can delete one that is open or not.
    --
    Mats
    The contents of the file that existed before are however deleted, so the effect is the same.
    Were nothing to be written to the file after the rm command (including a close command) it would be a goner.

    Of course the account only determines whether you have delete access at all, just thought to mention it to prevent someone asking why file XXX cannot be deleted by him but YYYY can

  14. #14
    chococoder
    Join Date
    Nov 2004
    Posts
    515
    Quote Originally Posted by zacs7 View Post
    > If you can write to open files, it can even be a security risk.
    That's what flockfile() is for... Bang supposed security risk gone (I can't even see how there would be one anyway...)
    If you could write to an executable that's being read by the operating system at that moment you could inject code in it that would be executed as well.
    Potential security risk I guess.

    Highly theoretical of course, far better to intercept the process after it's been loaded into memory and been validated as safe by virus scanners and change the instruction sequence there.

  15. #15
    Registered User
    Join Date
    Dec 2008
    Posts
    6
    are we getting off topic here :-P

    Any ideas whether my 2 possible reasons for this error are correct and/or how to resolve?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  2. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  3. Simple File encryption
    By caroundw5h in forum C Programming
    Replies: 2
    Last Post: 10-13-2004, 10:51 PM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Problem need help
    By Srpurdy in forum C++ Programming
    Replies: 1
    Last Post: 07-24-2002, 12:45 PM