c program to implement mv command

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

int main(int argc, char *argv[]) {
    if(argc != 3) {
        printf("Usage: mv <source_file> <destination_file>\n");
        exit(1);
    }

    if(rename(argv[1], argv[2]) == -1) {
        perror("mv");
        exit(1);
    }

    printf("File moved successfully.\n");

    return 0;
}

Explanation:

The above C program demonstrates the implementation of the mv command, which is used to move or rename files in a Unix-like operating system. Here's a step-by-step explanation of the program:

  1. Include necessary header files: The program includes two header files - stdio.h and stdlib.h. These header files provide the necessary functions and definitions for input/output operations and memory management.

  2. Define the main function: The main function is the entry point of the program. It takes two arguments: argc, an integer that represents the number of command-line arguments, and argv, an array of strings that contains the command-line arguments.

  3. Check the number of arguments: The program checks if the number of command-line arguments is equal to 3. If not, it prints a usage message and exits with a status of 1. The usage message instructs the user to provide two filenames: <source_file> and <destination_file>.

  4. Move or rename the file: If the number of arguments is correct, the program calls the rename function to move or rename the file. The rename function takes two arguments: the name of the source file (argv[1]) and the name of the destination file (argv[2]). If the rename function returns -1, indicating an error, the program prints an error message using the perror function and exits with a status of 1.

  5. Print success message: If the file is moved or renamed successfully, the program prints a success message.

  6. Return from the main function: The program returns 0 from the main function, indicating successful execution.

This program provides a basic implementation of the mv command in C. It can be compiled and executed to move or rename files in a Unix-like operating system.