Directory Handling in C++

A Directory or Folder is a file system object which contains group of files and folders or directory.

In C++, directory are handled by <dir.h> class which is used to manage the directory to create, remove and rename.

Below coding is the program for Directory Handling Operation:

#include <iostream.h>
#include <conio.h>
#include <process.h>
#include <dir.h>
char curd[MAXPATH];
char new_dir[MAXDIR];
void mkdir();
void removedir();
void curdir();
void redir();
char dir[9];
void main()
{

    int ch;
    clrscr();
    do
    {
     cout<<"\n\n\n\t1.Make Dir";
     cout<<"\n\t2.Remove Dir";
     cout<<"\n\t3.Current Dir\n\t4.Rename Dir\n\t5.Exit\nEnter ur choice:";
     cin>>ch;
     switch(ch)
     {
        case 1:
            mkdir();
            break;
        case 2:
            removedir();
            break;
        case 3:
            curdir();
            break;
        case 4:
            redir();
            break;
        case 5:
            exit(0);
            break;
        default:
            cout<<"\nInvalid choice:";
     }
    }while(ch!=5);
  getch();
}
void mkdir()
{
   int stat;
   clrscr();
   cout<<"\nEnter the new name:";
   cin>>dir;
   stat = mkdir(dir);
   if (!stat)
      cout<<"Directory created\n";
   else
   {
      cout<<"Unable to create directory\n";
      exit(1);
   }
   getch();
   system("dir/p");
   getch();

}
void removedir()
{
 int stat;
 clrscr();
 cout<<"\nEnter the new name to be deleted:";
 cin>>dir;
 stat = rmdir(dir);
 if(!stat)
    cout<<"\nDirectory deleted\n";
 else
 {
    cout<<"\nUnable to delete directory";
    exit(1);
 }
}
void curdir()
{
    getcwd(curd,MAXPATH);
    cout<<"current=>"<<curd[MAXPATH];
}

void redir()
{
  int stat,stat2;
  char tempname[9];
  cout<<"Enter the current directory name:";
  cin>>tempname;
  stat=rmdir(tempname);
  if(!stat)
  {
    cout<<"\nEnter new directory name:";

   l1:
    cin>>new_dir;
    stat2=mkdir(new_dir);
    if(!stat2)
        cout<<"\n\tDirectory Renamed";
    else
    {
        cout<<"\nDirectory name already exist";
        cout<<"\nEnter again:";
        goto l1;
    }
   }
   else
   cout<<"\n Directory does not exist";
}

 

Leave a Reply