简体   繁体   中英

Get permission denied error when trying to remove file

First of all hi everyone,

my problem is, that my program creates a file, which is read by another program and after hat my program should delete the file.

I use the following code below to check if the file exists and if any other program uses the file. After the that I want to delete the file with:

if(isFileRdy("C:\\test\\foo.txt"))remove("C:\\test\\foo.txt");

Does anyone have any idea, where the problem could be. Interestingly this works for other files. And the foo.txt is also created by this program without special access rights.

Thanks :)

/* just suppose the things with argc and argv work, I know it's uggly
   but I need it as a call back function later in the code */

BOOL isFileRdy(char *filePath)
{
    int argc = 1;
    void *argv[1];
    argv[0]= (void*) filePath;
    return isFileRdyCBF(argv, argc);
}


BOOL isFileRdyCBF(void *argv[], int argc)
{
/* I used */
    char *filePath = (char*) argv[0];
    FILE *fDes = NULL;
    BOOL _fileExists = FALSE;
    BOOL _fileBussy = TRUE;

    _fileExists = fileExists(filePath);

    if(_fileExists)
    {
        fDes = fopen(filePath, "a+");
        if(fDes!=NULL)
        {
            _fileBussy = FALSE;
            if(fclose(fDes)!=0)
            {
                printf("\nERROR could not close file stream!");
                printf("\n      '%s'\n\n", filePath);
                return FALSE;
            }
        }
    }

    return (_fileExists==TRUE && _fileBussy==FALSE) ? TRUE : FALSE;
}

This seems to be the problematic line (given that this is a snippet from int main(int argc, char **argv) :

char *filePath = (char*) argv[0];

Here you assign the program executable file to filePath, but not the first argument to the program. The first parameter is in argv[1] , but you must check first that argc >= 2 .

When you try to delete the file via a static path entry, you must escape the \\ -signs in your string with a second \\ :

remove("C:\\test\\foo.txt");

You say that it works for other files. What do these paths which work for you look like? Your whole problem could be that you are not using backslash \\ correctly.

In C, \\t means the tab character . So you wrote C:<TAB>test . To actually express the backslash character \\ in C, you write \\\\ . (This business of putting backslash before various characters to express special codes is called "escaping".)

For example, instead of remove("C:\\test\\foo.txt"); you would write remove("C:\\\\test\\\\foo.txt");

This should also work: remove("c:/test/foo.txt"); since Windows can also accept the forward slash / instead of backslash \\ in paths.

Also what Rudi said about argv.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM