Ivana Perić
Ivana Perić

Reputation: 1

Why do I get permission denied while deleting a file

I have a school project and I am getting an error from the remove function. It should be a simple function but I always get a "permission denied" error. I have checked that the file is not read only, etc.

This program is running on Windows 11.

Here is the function:

void deleteFile(const char* fileName) { 
    if (remove(fileName) == 0) {
         printf("File %s has been deleted!\n", fileName);
    }  
    else {
         perror("Error with file delete...");     
    }
}

Upvotes: -1

Views: 180

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50883

Your code is probably trying to delete an open file.

#include <stdio.h> 

void deleteFile(const char* fileName) {
  if (remove(fileName) == 0) {
    printf("File %s has been deleted!\n", fileName);
  }
  else {
    perror("Error with file delete...");
  }
}

int main() {
  FILE* f = fopen("somefile", "w");
  if (f == NULL)
  {
    perror("File could not be created");
    return;
  }

  // do something with f

  // fclose(f);   // <<< uncomment this and the deletion should work
  deleteFile("somefile");
}

This codes produces following output:

Error with file delete...: Permission denied

If you uncomment the line // fclose(f);, the file will be closed and the file removal should work.

Upvotes: 1

Related Questions