Click here to Skip to main content
Click here to Skip to main content

CFileManip: "DOS-Command-Like" File/Directory Manipulation

By , 28 Feb 2003
 

Sample Image - CFileManip_demo.gif

Introduction

Like many did, I started using computer when DOS 6.x was the main operating system, I was so used of it that now almost ten years passed and I still remember those DOS commands so very clearly, that like I was still typing them yesterday.

I do file/directory manipulation a lot in my programs, every time I wanted to copy or remove a directory including all its files and nested subdirectories to/from customers disk, I thought of those DOS commands, such as "xcopy", "deltree". Of course those can be done by API calls, but wouldn't it be more convenient if there is a class that can do such things by one single line of code, and wouldn't it be even cooler if the class methods look like DOS commands?

CFileManip, an API wrapping class that is developed to make file manipulation simpler and easier. The class itself basically offers "DOS command like" methods which are very similar to related DOS commands in both names and functionalities, I hope they bring you back to the good old time of DOS age.:-) Being able to use functions such as "xcopy" and "deltree" in my C++ code is what I always wanted to.

Progress windows are provided automatically during lengthy tasks. This class does not require MFC, thus may be used in any Win32 applications.

Class Member Methods

// File-only operations
static BOOL Copy(LPCTSTR lpSource, LPCTSTR lpDestination, BOOL bHidePrompt = TRUE);
static BOOL Del(LPCTSTR lpSource, BOOL bHidePrompt = TRUE);
static BOOL Ren(LPCTSTR lpSource, LPCTSTR lpDestination, BOOL bHidePrompt = TRUE);
Parameters
lpSource: Null terminated string that specifies path of source target. Wildcard allowed.
lpDestination: Null terminated string that specifies path of destination target.
bHidePrompt: If set to TRUE, no prompt or confirmation message windows will be displayed, otherwise those message windows may appear upon various situation.

Return value
Returns TRUE if the operation succeeded, FALSE otherwise.

Remarks
As their names explained, they do what DOS commands "copy"(copies files), "del"(deletes files) and "ren"(renames files) do. File-only operations, none of those methods are allowed to modify directories.

// File/directory operations
static BOOL XCopy(LPCTSTR lpSource, LPCTSTR lpDestination, BOOL bHidePrompt = TRUE);
static BOOL DelTree(LPCTSTR lpSource, BOOL bHidePrompt = TRUE);
static BOOL Move(LPCTSTR lpSource, LPCTSTR lpDestination, BOOL bHidePrompt = TRUE);

Parameters
lpSource: Null terminated string that specifies path of source target. Wildcard allowed.
lpDestination: Null terminated string that specifies path of destination target.
bHidePrompt: If set to TRUE, no prompt or confirmation message windows will be displayed, otherwise those message windows may appear upon various situation.

Return value
Returns TRUE if the operation succeeded, FALSE otherwise.

Remarks
As their names explained, they do what DOS commands "xcopy"(copies files or directory including subdirectories to target path, with all attributes and subdirectory structures inherited), "deltree"(deletes files or directory including subdirectories) and "move"(moves files or directory to target path) do. Those methods can modify both files and directories.

// Directory-only operations
static BOOL MkDir(LPCTSTR lpDirectory);
static BOOL RmDir(LPCTSTR lpDirectory);

Parameters
lpDirectory: Null terminated string that specifies directory name.

Return value
Returns TRUE if the operation succeeded, FALSE otherwise.

Remarks
Simple API calls. As their names explained, they do what DOS commands "mkdir"(create an empty directory), "rmdir"(deletes an empty directory. Those operations can not modify files.

// File/directory attributes access
static BOOL SetAttribute(LPCTSTR lpSource, DWORD dwNewAttr);
static DWORD GetAttribute(LPCTSTR lpSource);

Parameters
lpSource: Null terminated string that specifies path of source target.
dwNewAttr: A DWORD value that represents new attributes to be assigned to the source target. A complete list of attributes value can be found in MSDN "Platform SDK: Files and I/O: SetFileAttributes".

Return value
SetAttribute returns TRUE if the operation succeeded, FALSE otherwise.
GetAttribute returns a DWORD value that represents attributes of source target. A complete list of attributes value can be found in MSDN "Platform SDK: Files and I/O: GetFileAttributes".

Remarks
Set and get file or directory attributes.

// File/directory existence check
enum { FM_NOTEXIST = 0, FM_DIRECTORY, FM_FILE};
static int Existence(LPCTSTR lpSource);

Parameters
lpSource: Null terminated string that specifies path of source target.

Return value
Return value can be one of the following:
FM_NOTEXIST: Target does not exist.
FM_DIRECTORY: Target is an existing directory.
FM_FILE: Target is an existing file.

Remarks
Checks existence of a given target.

// Directory travelling
static BOOL CdDotDot(LPTSTR lpCurDirectory = NULL);

Parameters
lpCurDirectory: Null terminated string that will receives full path of current directory after this operation.

Return value
FALSE if current directory is the root directory of a driver, TRUE otherwise.

Remarks
This function does exactly what DOS command "cd.." does, to pull current directory backward(towards the root) one level in the directory tree structure. Calling ::GetCurrentDirectory before and after CdDotDot will show the difference.

History

Aug 3, 2002 - updated downloads.

Feb 12, 2003 - the class has been made UNICODE compliant.

Feb 23, 2003 - removed some unnecessary parts from source code.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Abin
China China
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralDeprecation warning with Visual 2005memberBerny2U21 Dec '06 - 23:54 
Hey Abin,
 
I like using this class, thankx. Big Grin | :-D
Did you know that when compiling under (C++) Visual Studio 2005 you get a depricate warning on the _tcsncpy functions ? OMG | :OMG:
 
Regards,

 
Bernard
GeneralDisc is readymemberGregor Schiller27 Jul '06 - 5:58 
Hi, pretty good work.
I have one question, perhaps you know.
Who can I check dirve a: is ready, that mean a disc is inserted?
thanks a lot.
Greg
 
Greg
GeneralBig problem , need helpmemberyousefk8 May '06 - 21:53 
I can't understand why not to use the standard C functions?
 
Directory-Control Routines
Routine Use
_chdir, _wchdir Change current working directory
_chdrive Change current drive
_getcwd, _wgetcwd Get current working directory for default drive
_getdcwd, _wgetdcwd Get current working directory for specified drive
_getdiskfree Populates a _diskfree_t structure with information about a disk drive.
_getdrive Get current (default) drive
_getdrives Returns a bitmask representing the currently available disk drives.
_mkdir, _wmkdir Make new directory
_rmdir, _wrmdir Remove directory
_searchenv, _wsearchenv

QuestionCopy all files into a folder no tree copysussBenito Loyola6 Sep '05 - 9:12 
I am looking for an application that will copy all files within a folder with several sub folders but copies only the files into one folder.
 
The purpose is time lapse file processing. The only items that the software can process are the images, but the camera software places the images in various daily, hourly and minute based folders and subfolders. Thus without having to cut & paste evey image...thousands...I hope there is a porgram that exists or can be easily be created for this function.
 
If one of the file names exists it needs to ask for a new file name or assign a new _X Copy name to it automatically.
 
Thank you
 
Please reply to benito @ loyola . com
 
Thank you.
GeneralMkDir is incomplete.memberAnthony_Yio3 Dec '04 - 18:31 
The dos version of mkdir will create the directories that make up the path in one call.
 
E.g.
 
mkdir C:\test\test2\test3\
 
three directories will be created if C:\test and C:\test\test2\ not exist.
 
but for ::CreateDirectory, it will only create the sub directory. C:\test\test2\test3\ will not succeed if C:\test and C:\test\test2 not exist.
 
Well, it is not difficult to do it but just that I think it should be there for completeness.
 
nice article by the way.
 
Sonork 100.41263:Anthony_Yio

GeneralPossible Problemsmembermehdi_cit2 Sep '04 - 22:35 
Hello everyone,
I came acros some problems when I tried to use some of the code present in this class (Thanks)!
I'm fairly new to windows, so I was using something like xcopy("C:/someDir","C:/someOtherDir");
Notice that I used the character / instead of \\ (comming from a Unix background).
It lead to some very strange behaviour of the program!
I should have used
xcopy("C:\\someDir","C:\\someOtherDir");
 
Which solved my problems.
 
Trust me always use \\ and never / with windows, even though the later works in 99% of the situations.
 
Hope it helps.

GeneralWhy use SHFILEOPTsussrelipse19 Jul '04 - 9:30 
I know you can use SHFileOperations to do all these things, but what about the idea of opening a command console and just doing a "copy blah blah";
 
Whattya think?
Might make it faster?
General8.3memberMB323 May '04 - 19:30 
nice class.
Nevertheless - I am wondering about a strange behaviour. From time to ime it happened that a wildcard copy command ended up in modifying the files to the MSDOS 8.3 structure, thereby cutting and modifying the orginal name (which is not really desirable).
 
I think it has something to do do with the double null terminated tchar.
Is there any way to circumenvent this problem.
I would lobe to use ths class.

 
http://superfluxus.de
GeneralI'm lost. (C++, filemanip.h)memberApollAthe17 Feb '04 - 1:11 
Hi, I am fairly new to C++ (Only about 6 monthes).   I am working on a program to go and delete the temporary internet files, cookies, and temp folder on a windows system.   I am tired of having the program making system calls to use deltree, and have been looking for a way to use deltree within the code without a system call.   So, when I found this page I was very happy to say the least, and estatic at most.Big Grin | :-D
 
But... now I can't get anything to work.   I use Dev C++ Ver. 4, and have dropped the filemanip.h header into my "include" directory, and it seems to be included fine, but I am getting odd errors, and I think it comes from not understanding how I am supposed to use the commands, and their syantx. Confused | :confused:
 
If anyone would take the time to explain how I can use this header I would be eternally thankful.
 

 
if (Spelling != True || Grammer != 0){
cout << "Sorry, my mind works more quickly than my fingers." << endl; }
GeneralRe: I'm lost. (C++, filemanip.h)member=[ Abin ]=17 Feb '04 - 2:00 
You need to tell us what kind of "odd errors" exactly happened, compiler error? Linker error? Runtime crash? We can only help after we know what's going on. And it'd be nice if you post some code snippet.
GeneralRe: I'm lost. (C++, filemanip.h)memberApollAthe17 Feb '04 - 2:30 
Oh, please excuse me for not giving code. I don't know where my mind is tonight.
 
Here is some of the code that I was trying with the header file, and the errors.
I've tryed various differant methods of defining the path from ('s to "'s, and both
together. I'm sure it is some simple mistake it my code. By the way, I am running Windows 2000, SP4.
 
Thanks tons!
 

 
#include
#include
#include
 
using namespace std;
 
int main()
{
 
DelTree "/y c:\\docume~1\\admini~1\\cookies\\";
system("PAUSE");
return 0;
}
 
Errors:
 
c:\docume~1\admini~1\mydocu~1\a-1.cpp: In function `int main()':
c:\docume~1\admini~1\mydocu~1\a-1.cpp:10: `DelTree' undeclared (first use this function)
c:\docume~1\admini~1\mydocu~1\a-1.cpp:10: (Each undeclared identifier is reported only once
c:\docume~1\admini~1\mydocu~1\a-1.cpp:10: for each function it appears in.)
c:\docume~1\admini~1\mydocu~1\a-1.cpp:10: parse error before string constant
 

 

#include
#include
#include
 
using namespace std;
 
int main()
{
 
static BOOL DelTree(LPCTSTR c:\\docume~1\\admini~1\\cookies\\, BOOL bHidePrompt = TRUE);
system("PAUSE");
return 0;
}
 

Errors:
 
c:\docume~1\admini~1\mydocu~1\a-2.cpp: In function `int main()':
c:\docume~1\admini~1\mydocu~1\a-2.cpp:10: possibly missing ')' before `:'
c:\docume~1\admini~1\mydocu~1\a-2.cpp:10: cannot declare static function inside another function
c:\docume~1\admini~1\mydocu~1\a-2.cpp:10: parse error before `:'
c:\docume~1\admini~1\mydocu~1\a-2.cpp:10: stray '\' in program
c:\docume~1\admini~1\mydocu~1\a-2.cpp:10: stray '\' in program
c:\docume~1\admini~1\mydocu~1\a-2.cpp:10: stray '\' in program
c:\docume~1\admini~1\mydocu~1\a-2.cpp:10: stray '\' in program
 

 
#include
#include
#include
 
using namespace std;
 
int main()
{
 
BOOL FileManip.h::DelTree "/y c:\\docume~1\\admini~1\\cookies\\";
system("PAUSE");
return 0;
}
 

Errors:
 
c:\docume~1\admini~1\mydocu~1\a-3.cpp: In function `int main()':
c:\docume~1\admini~1\mydocu~1\a-3.cpp:10: parse error before `.'
GeneralThanksmemberYVOTHI1 Dec '03 - 4:20 
You save me a lot of hours to understand API.
 
Thank you very much.
GeneralXcopy.memberCanopenR9 Oct '03 - 9:24 
How do you get Xcopy to copy the ACL information (the security info) form the files and folders to new file?
GeneralPlease show me ....memberchatter8 Oct '03 - 19:31 
Please show me codes of Dos Command ( md, dir, type )
Thanks !
 
chatter
GeneralThanksmemberskallestad2 Oct '03 - 15:32 
Just thought I'd drop a note to say thanks. This Class works perfect for me, and I was dreading figuring out how to use the Windows API.
GeneralANSI C++ Problemmembernon03225 Sep '03 - 16:05 
When I try to enter this code into my program it wouldnt work:
 
static BOOL DelTree(LPCTSTR c:/windows/desktop/doc.txt, BOOL bHidePrompt = TRUE);
 
It tells me that ANSI wont let the decleration BOOL with no type. What do I do?

GeneralHelp with accessing foldermembervgandhi13 Jun '03 - 8:42 
Hello,
I am trying to open a folder within the MFC code and get its files or subfolders . Can anyone help me out with how to go about doing this. Is there a class like CFolder that I can use.
Thank you.
 
vg
GeneralFile name from file handlememberbfadi24 Feb '03 - 7:41 
Hi , I don't think many people NEED this , BUT I NEED IT URGENTLY,
Please any one know how to get the file name from a file handle !
Thanks

GeneralRe: File name from file handlememberEric Lapouge2 Mar '03 - 21:23 
Hi,
 
Sam Blackburn did it for you...
 
For NT and over, you can find what you want at:
http://www.samblackburn.com/wfc/wfc_get_filename_from_handle.htm
 
Which is part of his library (wfc).
 
Regards,
 
EricBig Grin | :-D
Generalhellomemberarcotkalyan20 Feb '03 - 6:41 
i liked your work.but i am new to vc++.can you give me complete detail and explination of your work.Rose | [Rose] Smile | :)
GeneralSome comments...memberVictor Boctor13 Feb '03 - 12:00 
Interesting class... good work... Some comments below.
 
In the following code, you do not need the initialisation to _T("").
TCHAR szSource[MAX_PATH + 2 * sizeof(TCHAR)] = _T("");
	TCHAR szDestination[MAX_PATH + 2 * sizeof(TCHAR)] = _T("");
	::_tcsncpy(szSource, lpSource, MAX_PATH);
	::_tcsncpy(szDestination, lpDestination, MAX_PATH);
Also in both DelTree() and Move(), you change the current directory. In my opinion this is a side effect and should be fixed. The user requesting moving a file and not changing the current directory. Hence, I would suggest that you store the original directory, then revert to it. (I don't know if this will still be a problem in a multi-threaded application though!).
 
Regards,
Victor.
 
phpWebNotes is a page annotation system modelled after php.net.
http://webnotes.sourceforge.net/demo.php[^]
GeneralRe: Some comments...member=[ Abin ]=13 Feb '03 - 14:50 
Interesting class... good work... Some comments below.
 
Thanks. Smile | :)
 
In the following code, you do not need the initialisation to _T("")...
 
I agree. But this is just some sort of coding habit, people sometimes do stuff like this:
 
int n = 0;
n = SomeFunction();

 
The initialization of "= 0" isn't really needed, but the habit might help in the long run.
 
Also in both DelTree() and Move(), you change the current directory. In my opinion this is a side effect and should be fixed.
 
Nope, this is required by the operating system. You cannot delete a directory while which is the current directory, doing so will generate an error.
GeneralSpeedmemberG. Graeber14 Jan '03 - 23:51 
How can I get CFileManip faster?
It´s too slow!
 
regards
 
Gero
GeneralRe: Speedmember=[ Abin ]=13 Feb '03 - 14:37 
Well, all the internal work are done by API call ::SHFileOperation, until someone changes that API, you can't get it any faster.
Generallicensing questionmemberEugene Polonsky22 Nov '02 - 5:26 
Great article. Just wondering, what exactly does "All Rights Reserved" mean in your file headers? That seems to preclude any one of us using this source code.... Hope that's not the case....

 
----------------------------------------
----I said my name wasn't important
---------------------------SlartiBartFast

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 1 Mar 2003
Article Copyright 2002 by Abin
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid