Welcome to our deep dive into C Programming and managing multiple directories! In this tutorial, we'll explore how to create, navigate, and manipulate directories in your C programs. π―
Before we dive in, let's clarify what a directory is:
In C, we use the <stdio.h> and <stdlib.h> libraries to work with directories.
To create a new directory in C, we use the mkdir() function. Here's a simple example:
#include <stdio.h>
#include <stdlib.h>
int main() {
const char* dir_name = "new_directory"; // Name of the directory to be created
if(mkdir(dir_name, 0777) == -1) {
perror("Error creating directory");
return 1;
}
printf("Directory '%s' created successfully!\n", dir_name);
return 0;
}π Note: The mkdir() function returns 0 if the directory is created successfully, and -1 on failure. The second argument is the permission mode for the new directory.
To delete a directory in C, we use the rmdir() function. Here's an example:
#include <stdio.h>
#include <stdlib.h>
int main() {
const char* dir_name = "new_directory"; // Name of the directory to be deleted
if(rmdir(dir_name) == -1) {
perror("Error deleting directory");
return 1;
}
printf("Directory '%s' deleted successfully!\n", dir_name);
return 0;
}π Note: The rmdir() function returns 0 if the directory is deleted successfully, and -1 on failure. The directory being deleted must be empty.
To navigate to a directory in C, we use the chdir() function. Here's an example:
#include <stdio.h>
#include <stdlib.h>
int main() {
const char* dir_name = "new_directory"; // Name of the directory to navigate to
if(chdir(dir_name) != 0) {
perror("Error navigating to directory");
return 1;
}
printf("Navigated to directory '%s'\n", dir_name);
return 0;
}π Note: The chdir() function returns 0 if the change of directory is successful, and -1 on failure.
What function is used to create a new directory in C?
That's it for our introductory lesson on working with directories in C programming! As we delve deeper, we'll explore more advanced concepts and practical applications. Stay tuned! ππ»
Happy coding! π‘