Welcome to our comprehensive guide on the C chdir() function! This lesson is designed for beginners and intermediate learners, so let's dive right in. 🐳
chdir() Function? 📝The chdir() function in C is used to change the current working directory of the program. It's like moving around your computer's file system within your program.
chdir() Function? 💡You might want to use chdir() to access files that are located in a different directory than the one your program is currently in. For example, when reading or writing to files, it's often more convenient to work with files in the same directory as your program.
chdir() Function? 📝The syntax for the chdir() function is straightforward:
#include <stdio.h>
#include <stdlib.h>
int main() {
char* newDir = "new_directory"; // Replace with your desired directory
if (chdir(newDir) != 0) {
perror("Error changing directory");
return 1;
}
// Now you're in the new directory!
printf("Current working directory is now: %s\n", getcwd(NULL, 0));
return 0;
}Let's break this down:
stdio.h and stdlib.h.char* variable newDir to store the name of the directory we want to change to.chdir(newDir) to change the current working directory to newDir.Let's say you have a program in a directory called my_programs, and you have a file you want to read called data.txt in a subdirectory called data. Here's how you can change directories and read the file:
#include <stdio.h>
#include <stdlib.h>
int main() {
char* newDir = "data"; // Change to the 'data' directory
if (chdir(newDir) != 0) {
perror("Error changing directory");
return 1;
}
FILE* file = fopen("data.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Now you can read the file as usual
char buffer[100];
while (fgets(buffer, sizeof(buffer), file)) {
printf("%s", buffer);
}
fclose(file);
return 0;
}In this example, we first change to the data directory, then we open and read the data.txt file.
What does the `chdir()` function do in C?