Q:

C program to change the permissions of file using system() function

0

C program to change the permissions of file using system() function

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Given a file, we have to change the permissions of the file using the system() function by specifying the "chmod" command.

The system() function is a library function of <stdlib.h> or <cstdlib> header file which is used to execute the commands that can be executed in the command processor or the terminal of the operating system, and finally returns the command after it has been completed.

Syntax:

int system(const char *string);

The argument string is the command to be executed.

To change the permission of a file, create (form) the command using the chmod command and pass it into the system() function.

Program:

The source code to change the permissions of the file using the system() function is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to change the permissions of file
// using the system() function

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char fileName[16] = "file.txt";
    char cmd[32];
    int ret = 0;

    sprintf(cmd, "chmod 666 %s", fileName);

    ret = system(cmd);
    if (ret == 0)
        printf("Permissions of file changed successfully\n");
    else
        printf("Unable to change the permissions of file\n");

    return 0;
}

Output:

Permissions of file changed successfully

Explanation:

Here, we created a character array fileName, which is initialized with "file.txt". Then we changed the file permissions using the system() function by specifying the "chmod" command and printed the appropriate message on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

File Handling Examples Programs in C language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to capitalize the first letter of every ... >>
<< C program to rename a file using the system() func...