Get permission denied error when trying to remove file

1.4k Views Asked by At

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;
}
2

There are 2 best solutions below

0
On

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.

0
On

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");