File Management Programs in C++

  The previous article File Management in Windows using C++ discussed several File Management functions and their uses. Here, we shall discuss actual file management programs based on those functions. As mentioned previously, the tasks performed by these programs are of the following types :

a) Copying a File
b) Moving a File
c) Renaming a File
d) Deleting a File

File Management Programs

Sample program for copying a file

#include <Windows.h>
#include <iostream>
int main()
{
LPCTSTR exfile = L”D:\abc.txt”;
LPCTSTR nfile = L”D:\xyz.txt”;
BOOL chk = CopyFile(exfile, nfile, FALSE);
if (chk == TRUE)
std::cout << “The file was copied successfully :)”;
else
std::cout << “The file could not be copied :(“;
getchar();
return 0;
}

Sample program for moving a file

#include <Windows.h>
#include <iostream>
int main()
{
LPCTSTR exfile = L”D:\abc.txt”;
LPCTSTR nfile = L”G:\abc.txt”;
BOOL chk = MoveFile(exfile, nfile);
if (chk == TRUE)
std::cout << “The file was moved successfully :)”;
else
std::cout << “The file could not be moved :(“;
getchar();
return 0;
}

Sample program for renaming a file

#include <Windows.h>
#include <iostream>
int main()
{
LPCTSTR exfile = L”D:\abc.txt”;
LPCTSTR nfile = L”D:\xyz.txt”;
BOOL chk = MoveFile(exfile, nfile);
if (chk == TRUE)
std::cout << “The file was renamed successfully :)”;
else
std::cout << “The file could not be renamed :(“;
getchar();
return 0;
}

Sample program for deleting a file

#include <Windows.h>
#include <iostream>
int main()
{
LPCTSTR exfile = L”D:\abc.txt”;
BOOL chk = DeleteFile(exfile);
if (chk == TRUE)
std::cout << “The file was deleted successfully :)”;
else
std::cout << “The file could not be deleted :(“;
getchar();
return 0;
}

 

Note :

1. The program for moving a file and the one for renaming a file are nearly identical. The only thing that differs is that for renaming a file, the directory has to be the same for both arguments, while for moving a file, the directory name has to be different.

2. MoveFile () cannot replace existing files, therefore if the name of the new file may coincide with that of an existing file, you must replace MoveFile () with MoveFileEx ().
For ExampleMoveFile (exfile, nfile) would have to be replaced with MoveFileEx (exfile, nfile, FALSE).

We hope you understood the basic concept of File Management in Windows through these File Management Programs.

(Visited 258 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *