Rewinddir Function In C++

In this article, we will discuss the rewinddir function in C++ with its syntax, some information, and examples.

What is the rewinddir function in C++?

The rewinddir function is used to restore the directory stream's position to the beginning of the directory, dirp must call the rewinddir function. Similar to the opendir function, rewinddir also makes a directory stream to refer to the current state of the relevant directory.

Syntax:

It has the following syntax:

Example

#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.
  • Pseudocode:

  • 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).
  • Program 1:

Let us take an example to illustrate the rewinddir function in C++ .

Example

#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 us take another example to illustrate the rewinddir function in C++.

Example

#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:

Input Required

This code uses input(). Please provide values below: