In this guide, we will explore the rewinddir function in C++ along with its syntax, details, and illustrative examples.
What is the rewinddir function in C++?
The rewinddir function is employed to reset the position of the directory stream to the start of the directory. It is necessary for dirp to invoke the rewinddir function. Just like opendir function, rewinddir also causes a directory stream to point to the present status of the specific directory.
Syntax:
It has the following syntax:
#include <dirent.h>
void rewinddir(DIR *dirp)
Here are some additional information on the rewinddir function:
- Function Signature: The function signature is void rewinddir(DIR *dirp).
- Drip: Dirp is a pointer to a type of open directory called a directory stream.
- Purpose: The rewinddir function's goal is to reset the position indication for the directory stream that dirp points to the directory's beginning.
- Usage: Calling a rewinddir, and readdir(dirp) calls will start reading items from the beginning of the directory.
- Open a directory stream using opendir and store the pointer in d.
- Check whether d is NULL to handle any errors.
- Read and start processing the directory entries using readdir(d) until the end is reached.
- Reset the directory stream to the beginning using rewinddir(d).
- Read and start processing directory entries again from the beginning.
- Close the directory stream using closedir(d).
Pseudocode:
Program 1:
Let's consider a scenario to demonstrate the rewinddir function in C++.
#include <iostream>
#include <dirent.h>
int main() {
DIR *d;
struct dirent *entry;
d= opendir(".");
if (d == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(d)) != NULL) {
std::cout << entry->d_name << std::endl;
}
rewinddir(d);
std::cout << "\nAfter rewind:\n";
while ((entry = readdir(d)) != NULL) {
std::cout << entry->d_name << std::endl;
}
closedir(d);
return 0;
}
Output:
Program 2:
Let's consider another instance to demonstrate the rewinddir function in C++.
#include <iostream>
#include <dirent.h>
int main() {
DIR *d;
struct dirent *entry;
// Open the current directory
d = opendir(".");
if (d == NULL) {
perror("opendir");
return 1;
}
// Print the directory entries the first time
std::cout << "First listing:\n";
while ((entry = readdir(d)) != NULL) {
std::cout << entry->d_name << std::endl;
}
// Reset the directory stream to the beginning
rewinddir(d);
// Print the directory entries again
std::cout << "\nSecond listing:\n";
while ((entry = readdir(d)) != NULL) {
std::cout << entry->d_name << std::endl;
}
// Close the directory stream
closedir(d);
return 0;
}
Output: