==============================ModuleB===================================== | | | The program examples' source codes have been arranged in the same | | order that appeared in the Tutorial. This is unedited and unverified | | compilation. Published as is basis for educational, reacretional and | | brain teaser purposes. All trademarks, copyrights and IPs, wherever | | exist, are the sole property of their respective owner and/or | | holder. Any damage or loss by using the materials presented in this | | tutorial is USER responsibility. Part or full distribution, | | reproduction and modification is granted to any body. | | Copyright 2003-2005 © Tenouk, Inc. All rights reserved. | | Distributed through http://www.tenouk.com | | | | | =========================================================================== Compiled using VC++/VC++ .Net.....unmanaged... /*Playing with some of the file handling functions*/ #include #include #include #include #include /*You can try other files and directories*/ char obj[50] = "d:\\test\\testsubtwo\\testsubthree\\robots.txt"; char newobj[50] = "d:\\test\\testsubtwo\\testsubthree\\human.txt"; int main() { /*Check for existence*/ if((_access(obj, 0)) != -1) printf("%s file exists\n", obj); else printf("%s file does not exist lol!\n", obj); /*Check for read/write permission*/ if((_access(obj, 2)) != -1) printf("%s file has write permission\n", obj); if((_access(obj, 4)) != -1) printf("%s file has read permission\n", obj); if((_access(obj, 6)) != -1) printf("%s file has write and read permission\n\n", obj); /* Make file read-only: */ if(_chmod(obj, _S_IREAD) == -1) perror("File not found lol!\n"); else { printf("The file mode is changed to read-only\n"); _chmod(obj, _S_IREAD); } if((_access(obj, 4)) != -1) printf("%s file has read permission\n", obj); /*Change back to read/write*/ if(_chmod(obj, _S_IWRITE) == -1) perror("file not found lol!\n"); else { printf("\nThe file\'s mode is changed to read/write\n"); _chmod(obj, _S_IWRITE); } if((_access(obj, 2)) != -1) printf("%s file has write permission\n", obj); /*Attempt to rename file*/ int result = rename(obj, newobj); if(result != 0) printf("\nCould not rename %s\n", obj); else printf("\n%s file has been renamed to\n %s\n", obj, newobj); /*remove the file*/ if(remove(newobj) == -1) printf("\nCould not delete %s lol!\n", newobj); else printf("\nOoops! %s file has been deleted lol!\n", newobj); return 0; } ---------------------------------------------------------------------------------------------- /*This program uses _umask to set the file-permission mask so that all future files will be created as read-only files. Then we create a file for write and test opening the file for writing*/ #include #include #include #include #include int main() { int fh, oldmask; /*File in current working directory*/ char test[20] = "test.txt"; /*Create read-only files: */ oldmask = _umask(_S_IWRITE); printf("Oldmask = 0x%.4x\n", oldmask); /*create a file with write permission*/ fh = _creat(test, _S_IWRITE); if(fh == -1) printf("Couldn't create %s file!\n", test); else { printf("%s file successfully created.\n", test); _close(fh); } /*Try opening file for write*/ fh = _open(test, _O_WRONLY); if(fh == -1) printf("%s opening failed!\n", test); else { printf("%s opening succeeded!\n", test); if(_close(fh) == 0) printf("%s closed successfully!\n", test); } printf("Oldmask = 0x%.4x\n", oldmask); return 0; } ---------------------------------------------------------------------------------------------- /*Using the _stat64 function reporting a file information*/ #include #include #include #include int main() { struct __stat64 buf; int result; char fname[50] = "c:\\WINNT\\system32\\config\\sam.log"; /*Get data associated with a file*/ result = _stat64(fname, &buf); /*Test if statistics are valid*/ if(result != 0) printf("Problem getting %s file information.\n", fname); else { /*dump some of the file information*/ /*Notice how the structures' elements were accessed*/ printf("The file : %s\n", fname); printf("Drive : %c:\n", buf.st_dev + 'A'); printf("File size : %ld bytes\n", buf.st_size); printf("Time created : %s", _ctime64(&buf.st_ctime)); printf("Last accessed : %s", _ctime64(&buf.st_atime)); printf("Time modified : %s", _ctime64(&buf.st_mtime)); printf("Bit mask : %p\n", &buf. st_mode); return 0; } } ---------------------------------------------------------------------------------------------- /*Opening file for input and output, then close*/ /*Running on 32 bits system*/ #include #include #include #include #include int main() { int fhand1, fhand2; char fname1[50] = "cruntime.cpp"; char fname2[50] = "robots.txt"; fhand1 = _open(fname1, _O_RDONLY); if(fhand1 == -1) printf("opening %s failed for input\n", fname1); else { printf("%s opening succeeded for input\n", fname1); if(_close(fhand1) == 0) printf("%s closed successfully!\n", fname1); } fhand2 = _open(fname2, _O_WRONLY | _O_CREAT, _S_IREAD | _S_IWRITE); if(fhand2 == -1) printf("%s open failed for output\n", fname2); else { printf("%s open succeeded for output\n", fname2); if(_close(fhand2) ==0) printf("%s closed successfully!\n", fname1); } return 0; } ---------------------------------------------------------------------------------------------- /*Playing with directory, file and permission*/ #include #include #include #include #include #include #include int main(void) { int curdrive; char buffer[_MAX_PATH]; /*file name*/ char fname[20] = "content.doc"; /*path*/ char dir[50] = "d:\\test\\testsubtwo\\testsubthree"; struct _finddata_t c_file; /*file handle*/ long hFile; /*----------------------------------------------*/ printf("Firstly, get the current drive...\n"); curdrive = _getdrive(); printf("Current drive is %c:\n\n", curdrive + 'A'-1); /*-----------------------------------------------*/ printf("Next, get the current working directory...\n"); printf("Current working directory is: \n"); if(_getcwd(buffer, _MAX_PATH) == NULL) perror("_getcwd error lol!"); else printf("%s\n\n", buffer); /*-----------------------------------------------*/ printf("Change the current working directory...\n"); _chdir(dir); printf("\n"); /*------------------------------------------------*/ printf("Current working directory is: \n"); if(_getcwd(buffer, _MAX_PATH) == NULL) perror("_getcwd error"); else printf("%s\n\n", buffer); /*------------------------------------------------*/ hFile = _findfirst("*.*", &c_file); { printf("Listing of *.* files\n\n"); printf("\nRDO HID SYS ARC TYPE FILE DATE %19c SIZE\n", ' '); printf("--- --- --- --- ---- ---- ---- %19c ----\n", ' '); printf((c_file.attrib & _A_RDONLY) ? " Y " : " N "); printf((c_file.attrib & _A_HIDDEN) ? " Y " : " N "); printf((c_file.attrib & _A_SYSTEM) ? " Y " : " N "); printf((c_file.attrib & _A_ARCH) ? " Y " : " N "); printf((c_file.attrib & _A_NORMAL) ? " Y " : " N "); printf(" %-15s %.24s %6d\n", c_file.name, ctime(&(c_file.time_write)), c_file.size ); /*Find the rest of the files*/ while(_findnext(hFile, &c_file) == 0) { printf((c_file.attrib & _A_RDONLY) ? " Y " : " N "); printf((c_file.attrib & _A_HIDDEN) ? " Y " : " N "); printf((c_file.attrib & _A_SYSTEM) ? " Y " : " N "); printf((c_file.attrib & _A_ARCH) ? " Y " : " N "); printf((c_file.attrib & _A_NORMAL) ? " Y " : " N "); printf(" %-15s %.24s %6d\n", c_file.name, ctime(&(c_file.time_write)), c_file.size); } _findclose(hFile); } /*Check the file exist...*/ if((_access(fname, 0)) != -1) printf("\n%s file exists\n", fname); else { printf("\n%s file not found lor!\n", fname); /*just exit*/ exit(1); } /*Check the permission*/ printf("\nTest the permission for %s file\n", fname); /*If write, then change to read. Must check the write first because file that can be write can also be read but not vice versa*/ if((_access(fname, 2)) == 0) { printf("\n%s file has write permission!\n", fname); printf("\nChange to read only permission...\n"); _chmod(fname, _S_IREAD); printf("\nRetest the read only permission...\n"); if((_access(fname, 4)) == 0) printf("%s file is READ ONLY!\n", fname); exit(0); } /*if not write it should be read permission, then change to write permission*/ else { printf("\n%s file is READ ONLY!\n", fname); printf("\nChange to write permission...\n"); _chmod(fname, _S_IWRITE); printf("\nRetest for write permission..."); if((_access(fname, 2)) == 0) printf("\n%s has write permission!\n", fname); exit(0); } return 0; } ---------------------------------------------------------------------------------------------- /*****program example using bsearch()*****/ /*****If it is C++, better to use STL****/ #include #include #include /*A compare function prototype*/ int compare(char **arg1, char *arg2[]); int main(int argc, char *argv[]) { char **result; char *key = "red"; int i; /*Sort using qsort algorithm*/ qsort((void *)argv, (size_t)argc, sizeof(char *), (int (*)(const void*, const void*))compare); /*Output the sorted list */ for(i = 0; i < argc; ++i) printf("%s ", argv[i]); /*Find the word "cat" using a binary search algorithm*/ result = (char **)bsearch((char *) &key, (char *)argv, argc, sizeof(char *), (int (*)(const void*, const void*))compare); if(result) printf("\n\'%s\' word found at address: %p\n", *result, result); else printf("\n\'%s\' word not found!\n", *result); return 0; } int compare(char *arg1[], char *arg2[]) { /*Compare all of both strings*/ return _strcmpi(*arg1, *arg2); } ---------------------------------------------------------------------------------------------- /*Playing with time. Program example for time management functions...*/ #include #include #include #include #include int main() { char buff[128], ampm[] = "AM"; __time64_t lgtime; struct __timeb64 timstruct; struct tm *today, *thegmt, xmas = {0, 0, 12, 25, 11, 90}; /* Set time zone from TZ environment variable. If TZ is not set, * the operating system is queried to obtain the default value * for the variable.*/ _tzset(); /*Get UNIX-style time and display as number and string.*/ _time64(&lgtime); printf("Time in seconds since UTC 1/1/70:\t%ld seconds\n", lgtime); printf("UNIX time and date:\t\t\t%s", _ctime64(&lgtime)); /*Display UTC.*/ thegmt = _gmtime64(&lgtime); printf("Coordinated universal time, UTC:\t%s", asctime(thegmt)); /*Display operating system-style date and time.*/ _strtime(buff); printf("OS time:\t\t\t\t%s\n", buff); _strdate(buff); printf("OS date:\t\t\t\t%s\n", buff); /*Convert to time structure and adjust for PM if necessary.*/ today = _localtime64(&lgtime); if(today->tm_hour >= 12) { strcpy(ampm, "PM"); today->tm_hour -= 12; } /*Adjust if midnight hour.*/ if(today->tm_hour == 0) today->tm_hour = 12; /* Pointer addition is used to skip the first 11 * characters and printf() is used to trim off terminating * characters.*/ printf("12-hour time:\t\t\t\t%.8s %s\n", asctime(today) + 11, ampm); /*Print additional time information.*/ _ftime64(&timstruct); printf("Plus milliseconds:\t\t\t%u\n", timstruct.millitm); printf("Zone difference in hours from UTC:\t%u hours\n", timstruct.timezone/60); printf("Time zone name:\t\t\t\t%s\n", _tzname[0]); printf("Daylight savings:\t\t\t%s\n", timstruct.dstflag ? "YES" : "NOT SET"); /*Make time for noon on Christmas, 1990.*/ if(_mktime64(&xmas) != (__time64_t)-1) printf("Christmas\t\t\t\t%s", asctime(&xmas)); /*Use time structure to build a customized time string.*/ today = _localtime64(&lgtime); /*Use strftime to build a customized time string.*/ strftime(buff, 128, "Today is %A, day %d of %B in the year %Y.\n", today); printf(buff); return 0; } ----------------------------------------------------------------------------------------------------------------- #include #include #include #include #include #include #include int main() { char fname[20] = "testnofile.txt"; int fhndl; /*Try to open non-existing file*/ if((fhndl = _open(fname, _O_RDONLY)) == -1) { /*Using the possible ways to create error message*/ perror("Using perror()"); printf("Using strerror(): %s\n", strerror(errno)); printf(_strerror("_strerror()")); printf("There is some error opening %s file\n", fname); } else { printf("Open %s for reading succeeded!\n", fname); _close(fhndl); } return 0; } ---------------------------------------------------------------------------------------------- /***** mysearch.cpp *********/ /*Compiled using VC++ 7.0/.Net*/ /*Run at command prompt */ /*Tested on Win Xp Pro machine*/ #include #include #include #include #include #include #include #include /*Prototype for recursive function*/ void FindThePath(TCHAR*, TCHAR*, TCHAR*); /*Filename stripping*/ static void TheRightside(TCHAR *str, size_t num) { size_t i = _tcslen(str); size_t chs = 0, chr = 0; /*May use malloc() for C compiler*/ TCHAR *hld = new TCHAR[num+1]; if((i > num) || (i == num)) { for(chs = (i-num); chs 0) { /*modify it to search for all files/folders....*/ _tcscpy(start, root); _tcscat(start, "\\*"); } for(hFind = FindFirstFile(start, &fd), ok = 1; hFind != INVALID_HANDLE_VALUE && ok; ok = FindNextFile(hFind, &fd)) { //bitwise AND to test the returned fileattributes if(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { /*assuming it is a dir so copy over*/ _tcscpy(dir, fd.cFileName); /*make sure it is not the default parent directory...*/ if((TestTheStrings(dir, ".") == false)) { /*Or current working directory, copying this over results in infinite recursion*/ if((TestTheStrings(dir, "..") == false)) { if(found == false) /*if we have not found the file in this current call, then make a call*/ { /*Constructs the path*/ /*Or you can try the _fullpath()*/ _tcscpy(test, root); _tcscat(test, "\\"); _tcscat(test, dir); /*and recurse through them.....*/ FindThePath(test, file, buffer); }/*end found*/ }/*end .. test*/ }/*end . test*/ }/*end dir test*/ /*bitwise AND to check for file flag*/ if(fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN) { /*if we have a file is it the one we want?*/ found = TestTheStrings(file, fd.cFileName); if(found == true) { /*if it is, then create the full path name for it and copy into the buffer*/ _tcscpy(buffer, root); _tcscat(buffer, "\\"); _tcscat(buffer, fd.cFileName); printf("%s\n", buffer); /*-----------------------------------------------------------------*/ /*Other routines can be implemented/called here for the found files*/ /*Such as delete, rename, replace, search the file contents, */ /*move, append, create a file, change the file attributes etc... */ /*-----------------------------------------------------------------*/ }/*end found test*/ }/*end archive test*/ }/*end for*/ /*18 = ERROR_NO_MORE_FILES, that is if other than no more files...*/ /*Check the error if any*/ if(GetLastError() != 18) printf("FindFile() error: %d\n", GetLastError()); if(hFind != INVALID_HANDLE_VALUE) { BOOL ok = FindClose(hFind); if(!ok) /*Check the last error if any, very good for troubleshooting/debug*/ printf("FindClose() error: %d", GetLastError()); } } /*The main() program*/ int main(int argc, char *argv[]) { TCHAR buffer[_MAX_PATH]; TCHAR mydrives[] = "A:"; /*If not enough arguments supplied*/ if(argc != 2) { printf("Example usage: %s or or <*.txt> or <*.*>\n", argv[0]); printf("It is case sensitive!\n"); /*Just exit*/ exit (-1); } /*Some prompt*/ printf("Example usage: %s or or <*.txt> or <*.*>\n", argv[0]); printf("It is case sensitive!\n\n"); /*Get the drives bit masks...1 is available, 0 is not available*/ /*A = least significant bit...*/ ULONG DriveMask = _getdrives(); /*If something wrong*/ if(DriveMask == 0) printf("_getdrives() failed with failure code: %d\n", GetLastError()); while(DriveMask) { printf("Found %s and start digging...\n", mydrives); if(DriveMask & 1) printf(mydrives); /*For every found drive...do the file search*/ FindThePath(mydrives, argv[1], buffer); /*Pointer increment*/ ++mydrives[0]; /*Shift the bit masks binary*/ /*to the right and repeat, means go to the next found drive*/ DriveMask >>= 1; } return 0; } ========================================================================================================