Home > Enterprise >  C remove() and rename() gives "Permission error"
C remove() and rename() gives "Permission error"

Time:03-03

I can't figure out what is happening in my program, it's a simple function to clear all the Windows '\r' from a file, putting all the chars in another file and then rename it to substitute the old file. Every time I execute the function the rename() and remove() functions give me "Permission error" even if I had all the file pointers closed and the file on my PC is closed in every program. Here's the code

static bool correctFile(string fileName) {
        string name = fileName;
        FILE* test = fopen(fileName.c_str(), "rb");
        FILE *in, *out;
        char stringTest[1000];
        bool isWinFile = false;
        if (!test) {
            return false;
        }
        fread(stringTest, 1, 1000, test);
        fclose(test);
        for (size_t i = 0; i < strlen(stringTest) && !isWinFile; i  ) {
            if (stringTest[i] == '\r') {
                isWinFile = true;
            }
        }
        if (isWinFile) {
            in = fopen(fileName.c_str(), "rb");
            string tempFile = name   ".temp";
            out = fopen(tempFile.c_str(), "wb");
            if (!in || !out) {
                return false;
            }
            char temp;
            while (fread(&temp, sizeof(temp), 1, in) > 0) {
                if (temp != '\r') {
                    fwrite(&temp, sizeof(temp), 1, out);
                }
            }
            fclose(in);
            fclose(out);
            if (std::remove(fileName.c_str())) {
                std::cerr << "Error: " << strerror(errno);
                return false;
            }
            if (std::rename(tempFile.c_str(), fileName.c_str())) {
                return false;
            }
        }
        return true;
    }

If you find an error in this please tell me, thanks

CodePudding user response:

I found out that the old file and the new file must not be in the same folder for some reason

CodePudding user response:

Disable the virus scanner and see if the problem persists. Some antivirus products block access to files for a couple of microseconds after they have been written or modified. I know of Kaspersky for example.

I have a "Antivirus" retry loop in some of my batch files because of this. So one (ugly) solution is to retry the rename/remove operations a couple of times.

  •  Tags:  
  • c
  • Related