×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to rename a file using the system() function

Here, we are going to learn how to rename a file using the system() function using C program?
Submitted by Nidhi, on August 14, 2021

Problem statement

Read the old and new filename, and then rename the given file using the system() function by specifying the "mv" command.

Renaming a file using the system() function

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 rename a file, create (form) mv command with old and new file names and pass it into the system() function.

C program to rename a file using the system() function

The source code to rename a 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 rename a file
// using the system() function.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char oldName[16];
    char newName[16];
    char cmd[64];

    int ret = 0;

    printf("Enter old filename: ");
    scanf("%s", oldName);

    printf("Enter new filename: ");
    scanf("%s", newName);

    sprintf(cmd, "mv %s %s", oldName, newName);
    ret = system(cmd);

    if (ret == 0)
        printf("File renamed successfully\n");
    else
        printf("Unable to rename file\n");

    return 0;
}

Output

Enter old filename: file.txt
Enter new filename: newfile.txt
File renamed successfully

Explanation

Here, we created two character arrays oldName, newName. Then we read the old and new names of files from the user. Then we renamed the given file using the system() function by specifying the "mv" command and printed the appropriate message on the console screen.

C File Handling Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.