Home :: Programming :: Code Snippets :: MfcWin :: Changing File Attributes with Mfc
[ Changing File Attributes with Mfc ]
If you intend to change the filename of a file or simply to modify the creation date then you're right here. Indeed doing so isn't that difficult under Windows. But at first you have to add the following enum to your code that lists all possible fileattributes (stdafx.h is okay):
normal = 0x00, //a normal file
readOnly = 0x01, //read-only, can't write into the file
hidden = 0x02, //likes to hide..
sys = 0x04, //system file
volume = 0x08, //seems to be a harddisk after MSDN help
directory = 0x10, //guess..
archive = 0x20 //don't know what Windows means by that..
To get the attributes of a file, you have to use CFile::GetStatus(..). The good thing about this function is, that there's both a version that can be called on an exisiting CFile object and a static version that can be used without creating a CFile object.
BOOL GetStatus( CFileStatus& rStatus ) const;
static BOOL PASCAL GetStatus( LPCTSTR lpszFileName, CFileStatus& rStatus );
//file information struct
CTime m_ctime; //date of creation
CTime m_mtime; //date when last modified
CTime m_atime; //date when last accessed
LONG m_size; //size in bytes (1 KByte = 1024 bytes)
BYTE m_attribute; //OR'd attributes (see above)
char m_szFullName[_MAX_PATH]; //the filename itself
The CFileStatus contains all necessary - and perhaps unnecessary information - about a file. After saving the data into a CFileStatus struct using CFile::GetStatus(..), this data can be modified and saved with CFile::SetStatus(..) later on which works exactely like GetStatus(..).
Note: when changing the time stamps of a file, the m_mtime - last modfied date - field has to be changed too otherwise Windows won't know that something has been changed. This isn't necessary when changing the file attributes. Last but not least here's a little code example:
CString filename = "test.dat";
//change last access date
CTime lastAccess = fileStatus.m_atime;
//modify (new date/time : 10:10:10, 1989-12-12)
lastAccess = CTime(1989,12,12,10,10,10);
//m_mtime must always be changed
fileStatus.m_mtime = lastAccess;
//change access date too and noone will notice anything ;-)
fileStatus.m_atime = lastAccess;
//as a little gimmick, we'll change the file attributes too
fileStatus.m_attribute = readOnly | hidden;
This method has also been used in FileEditor so if you want to see a real life example, check out the source code. But I think everything should be clear by now and if it's not so, visit the message board. Happy Coding!