Search code examples
cfiledirectoryfile-permissionschmod

C - chmod() not changing permissions


I am trying to change the permissions of a bunch of files that are located in a specific directory. I am using chmod to do so. The function does not return any error, but when I print the old and new permissions, it does not look like it is changing anything.

void main(int argc, char *argv[]){
    struct stat archivo;    
    char *directorio = "/home/edu/Escritorio/P7/practica7/prueba";
    char *rutaRel = malloc(strlen(directorio) + 1 + NAME_MAX);
    mode_t permisos;

    modo = strtol(argv[2], NULL, 0);    //I am trying with 0664

    strcpy(rutaRel, directorio);
    rutaRel[strlen(directorio)] = '/';
    while (ep = readdir (dp)){
        strcpy(rutaRel + strlen(directorio) + 1, ep->d_name);
        stat(rutaRel, &archivo);
        if(S_ISREG(archivo.st_mode)){
            permisos=archivo.st_mode;
            if((chmod(rutaRel,modo))==-1){
                perror("Error: \n");
            }
            printf("  %s: %u -> %u\n",ep->d_name,permisos,archivo.st_mode); 
        }
    }   

    closedir(dp);
}

I have not been able to locate the error so far. Any ideas?

OUTPUT:

a4: 33204 -> 33204

a2: 33204 -> 33204

A3: 33204 -> 33204

a5: 33204 -> 33204

a1: 33204 -> 33204


Solution

  • The problem is that you don't get the new flags for the file, you print the same old flags you fetched before calling chmod.