How to remove and rename directories in C language?

Asked

Viewed 789 times

2

To create a directory I used the mkdir(const char*) function and to remove I tried to use remove(const char*),as below:

void remove_diretorio() {
 char nome_pasta[10];
 printf("Informe o nome da pasta: ");
 fflush(stdin);
 gets(nome_pasta);
 if(remove(nome_pasta)) {
     Sleep(500);
     printf("Erro ao exlcluir o diretorio!\n");
     printf("%s",strerror(errno));
     system("pause");
     return;
 } else {
     Sleep(500);
     printf("Pasta excluída com sucesso\n");
     system("pause");
 }
}

However the return is being different from zero, as it is entering my if. I need to rename also and I can not find references.

Note: remove_directory() is a function of my program; my operating system is Windows.

  • apart: this is probably a program for personal use and you’re not worrying too much about security - so, ok use the gets passing a fixed size string (char nome_pasta[10] - (the recommendation is to use fgets) . However, even for personal use, the 10 byte size is almost SURE to be exceeded in a filename - it may result in your program being terminated by S.O. - but someone knowing your program by typing more than 10 characters can change the value of other internal variables, for example. That would be a "buffer overrun attack"

1 answer

0


I don’t know much about C and its architecture, but I know it’s very similar to C++, it might be wrong, but I found this function to delete a directory that is not empty:

int remove_directory(const char *path)
{
   DIR *d = opendir(path);
   size_t path_len = strlen(path);
   int r = -1;

   if (d)
   {
      struct dirent *p;

      r = 0;

      while (!r && (p=readdir(d)))
      {
          int r2 = -1;
          char *buf;
          size_t len;

          /* Skip the names "." and ".." as we don't want to recurse on them. */
          if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
          {
             continue;
          }

          len = path_len + strlen(p->d_name) + 2; 
          buf = malloc(len);

          if (buf)
          {
             struct stat statbuf;

             snprintf(buf, len, "%s/%s", path, p->d_name);

             if (!stat(buf, &statbuf))
             {
                if (S_ISDIR(statbuf.st_mode))
                {
                   r2 = remove_directory(buf);
                }
                else
                {
                   r2 = unlink(buf);
                }
             }

             free(buf);
          }

          r = r2;
      }

      closedir(d);
   }

   if (!r)
   {
      r = rmdir(path);
   }

   return r;
}

(Source)

To rename, use the function rename(oldFilename, newFilename). Reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.