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:
Include necessary header files: The program includes two header files -
stdio.h
andstdlib.h
. These header files provide the necessary functions and definitions for input/output operations and memory management.Define the
main
function: Themain
function is the entry point of the program. It takes two arguments:argc
, an integer that represents the number of command-line arguments, andargv
, an array of strings that contains the command-line arguments.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>
.Move or rename the file: If the number of arguments is correct, the program calls the
rename
function to move or rename the file. Therename
function takes two arguments: the name of the source file (argv[1]
) and the name of the destination file (argv[2]
). If therename
function returns -1, indicating an error, the program prints an error message using theperror
function and exits with a status of 1.Print success message: If the file is moved or renamed successfully, the program prints a success message.
Return from the
main
function: The program returns 0 from themain
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.