What are in this Module?
System Calls
System Call Functions
File Handling
File-Handling Functions (Files)
File-Handling Functions (Path or Filename)
Program examples
|
My Training Period: zz hours. Before you begin, read some instruction here.
Abilities that supposed to be acquired:
System Calls
|
|
Function |
Use |
|
_findclose() |
Release resources from previous find operations. |
|
_findfirst(), _findfirst64(), _findfirsti64(), _wfindfirst(), _wfindfirst64(), _wfindfirsti64() |
Find file with specified attributes. |
|
_findnext(), _findnext64(), _findnexti64(), _wfindnext(), _wfindnext64(), _wfindnexti64() |
Find next file with specified attributes. |
|
Table 9: System call functions |
|
|
Element/field |
Description |
|
unsigned attrib |
File attribute. |
|
time_t time_create |
Time of file creation (–1L for FAT file systems). |
|
time_t time_access |
Time of last file access (–1L for FAT file systems). |
|
time_t time_write |
Time of last write to file. |
|
_fsize_t size |
Length of file in bytes. |
|
char name[_MAX_FNAME] |
Null-terminated name of matched file/directory, without the path. _MAX_FNAME is defined in stdlib.h as 256 bytes. |
|
Table 10: _finddata_t structure information |
|
|
attrib |
Description |
_A_ARCH |
Archive. Set whenever the file is changed, and cleared by the BACKUP command. Value: 0x20. |
_A_HIDDEN |
Hidden file. Not normally seen with the DIR command, unless the /AH option is used. Returns information about normal files as well as files with this attribute. Value: 0x02. |
_A_NORMAL |
Normal. File can be read or written to without restriction. Value: 0x00. |
_A_RDONLY |
Read-only. File cannot be opened for writing, and a file with the same name cannot be created. Value: 0x01. |
_A_SUBDIR |
Subdirectory. Value: 0x10. |
_A_SYSTEM |
System file. Not normally seen with the DIR command, unless the /A or /A:S option is used. Value: 0x04. |
|
Table 11: attrib return value |
|
|
Information |
Description |
|
The function |
_findclose(). |
|
The use |
Closes the specified search handle and releases associated resources. |
|
The prototype |
int _findclose(intptr_t handle); |
|
Example |
struct _finddata_t c_file; long hFile; hFile = _findfirst("*.*", &c_file); _findclose(hFile); |
|
The parameters |
handle - Search handle returned by a previous call to _findfirst(). |
|
The return value |
If successful, _findclose() returns 0. Otherwise, it returns –1 and sets errno to ENOENT, indicating that no more matching files could be found. |
|
The header file |
<io.h>. |
|
Table 12: _findclose() function information |
|
|
Information |
Description |
|
The function |
_findfirst(), _findfirst64(), _findfirsti64(), _wfindfirst(), _wfindfirst64(), _wfindfirsti64(). |
|
The use |
Provide information about the first instance of a filename that matches the file specified in the filespec argument. |
|
The prototype |
intptr_t _findfirst( const char *filespec, struct _finddata_t *fileinfo ); intptr_t _findfirst64( const char *filespec, struct __finddata64_t *fileinfo );
intptr_t _findfirsti64( const char *filespec, struct _finddatai64_t *fileinfo );
intptr_t _wfindfirst( const wchar_t *filespec, struct _wfinddata_t *fileinfo );
intptr_t _wfindfirst64( const wchar_t *filespec, struct __wfinddata64_t *fileinfo );
intptr_t _wfindfirsti64(const wchar_t *filespec, struct _wfinddatai64_t *fileinfo ); |
|
Example |
struct _finddata_t c_file; long hFile;
hFile = _findfirst("*.*", &c_file); |
|
The parameters |
filespec - Target file specification (may include wildcards). fileinfo - File information buffer. |
|
The return value |
If successful, _findfirst() returns a unique search handle identifying the file or group of files matching the filespec specification, which can be used in a subsequent call to _findnext() or to _findclose(). Otherwise, _findfirst() will return –1 and set errno to one of the following values: ENOENT - File specification that could not be matched. EINVAL - Invalid filename specification. |
|
The header file |
<io.h> or <wchar.h> for _wfindfirst(), _wfindfirst64(), _wfindfirsti64(). |
|
Table 13: _findfirst() family function information |
|
|
Information |
Description |
|
The function |
_findnext(), _findnext64(), _findnexti64(), _wfindnext(), _wfindnext64(), _wfindnexti64(). |
|
The use |
Find the next name, if any, that matches the filespec argument in a previous call to _findfirst(), and then alter the fileinfo structure contents accordingly. |
|
The prototype |
int _findnext( intptr_t handle, struct _finddata_t *fileinfo ); int _findnext64( intptr_t handle, struct __finddata64_t *fileinfo );
int _findnexti64( intptr_t handle, struct _finddatai64_t *fileinfo ); int _wfindnext( intptr_t handle, struct _wfinddata_t *fileinfo );
int _wfindnext64( intptr_t handle, struct __wfinddata64_t *fileinfo );
int _wfindnexti64( intptr_t handle, struct _wfinddatai64_t *fileinfo ); |
|
Example |
struct _finddata_t c_file; long hFile; _findnext(hFile, &c_file); |
|
The parameters |
handle - Search handle returned by a previous call to _findfirst(). fileinfo - File information buffer. |
|
The return value |
If successful, return 0. Otherwise, return –1 and sets errno to ENOENT, indicating that no more matching files could be found. |
|
The header file |
<io.h> or <wchar.h> for _wfindnext(), _wfindnext64(), _wfindnexti64(). |
|
Table 14: _findnext() family function information |
|
/* the use of the 32-bit _find() functions to print a list of all files (and their attributes) in the current directory. */
#include <stdio.h>
#include <io.h>
#include <time.h>
#include <direct.h>
#include <conio.h>
#include <ctype.h>
int main()
{
// for XP, char path[50] = "C:\\Windows\\System32\\config";
char path[50] = "C:\\WINNT\\System32\\config";
struct _finddata_t c_file;
long hFile;
printf("Change to %s\n", path);
if(_chdir(path))
printf("Unable to locate the directory: %s\n", path);
else
/* find first in the current directory */
/* hFile = (long) _findfirst("*.*", &c_file); */
hFile = _findfirst("*.*", &c_file);
/* list the files... */
printf("Listing of files in the directory %s\n\n", path);
printf("\nRDO HID SYS ARC FILE DATE %25c SIZE\n", ' ');
printf("--- --- --- --- ---- ---- %25c ----\n", ' ');
printf((c_file.attrib & _A_RDONLY) ? " Y " : " N ");
printf((c_file.attrib & _A_SYSTEM) ? " Y " : " N ");
printf((c_file.attrib & _A_HIDDEN) ? " Y " : " N ");
printf((c_file.attrib & _A_ARCH) ? " Y " : " N ");
printf(" %-12s %.24s %9ld\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_SYSTEM) ? " Y " : " N ");
printf((c_file.attrib & _A_HIDDEN) ? " Y " : " N ");
printf((c_file.attrib & _A_ARCH) ? " Y " : " N ");
printf(" %-12s %.24s %9ld\n", c_file.name, ctime(&(c_file.time_write)), c_file.size);
}
_findclose(hFile);
return 0;
}
The output sample:
|
Change to C:\WINNT\System32\config Listing of files in the directory C:\WINNT\System32\config
RDO HID SYS ARC FILE DATE SIZE --- --- --- --- ---- ---- ---- N N N Y . Sat Jun 05 14:23:34 2004 0 N N N Y .. Sat Jun 05 14:23:34 2004 0 N N N Y AppEvent.Evt Thu May 12 01:18:44 2005 65536 N N N Y default Tue May 17 20:07:50 2005 147456 N N Y Y default.LOG Tue May 17 20:07:50 2005 1024 N N N Y default.sav Sat Jun 05 07:06:31 2004 81920 N N N Y netlogon.ftl Wed Jun 16 02:08:51 2004 112 N N N Y SAM Tue May 17 20:08:13 2005 32768 N N Y Y SAM.LOG Tue May 17 20:08:13 2005 1024 N N N Y SecEvent.Evt Sat Jun 05 14:26:09 2004 65536 N N N Y SECURITY Tue May 17 20:17:21 2005 49152 N N Y Y SECURITY.LOG Tue May 17 20:17:21 2005 1024 N N N Y software Tue May 17 20:42:37 2005 26300416 N N Y Y software.LOG Tue May 17 20:42:37 2005 1024 N N N Y software.sav Sat Jun 05 07:06:31 2004 540672 N N N Y SysEvent.Evt Tue May 17 01:27:36 2005 524288 N N N Y system Tue May 17 20:08:52 2005 3072000 N N N Y SYSTEM.ALT Tue May 17 20:08:53 2005 3076096 N N Y Y system.LOG Sat Jun 05 07:06:31 2004 1024 N N N Y system.sav Sat Jun 05 07:06:31 2004 372736 N N Y Y TempKey.LOG Sat Jun 05 07:06:28 2004 0 N N N Y userdiff Sat Jun 05 07:06:31 2004 139264 N N Y Y userdiff.LOG Sat Jun 05 07:06:31 2004 1024 Press any key to continue |
The following is output sample tested on Win XP Pro SP2 using Visual C++ Express Edition 2005 with Windows SDK installed.

|
Function |
Use |
|
_chsize() |
Change the file size. |
|
_filelength() |
Get file length. |
|
_fstat(), _fstat64(), _fstati64() |
Get file-status information on handle. |
|
_isatty() |
Check for character device. |
|
_locking() |
Lock areas of file. |
|
_setmode() |
Set file-translation mode. |
|
Table 15: File handling functions for files |
|
|
Information |
Description |
|
The function |
_chsize(). |
|
The use |
Changes the file size. |
|
The prototype |
int _chsize(int handle, long size); |
|
Example |
int fhdl; _chsize(fhdl, 123456); |
|
The parameters |
handle - Handle referring to open file. size - New length of file in bytes. |
|
The return value |
_chsize() returns the value 0 if the file size is successfully changed. A return value of –1 indicates an error: errno is set to EACCES if the specified file is locked against access, to EBADF if the specified file is read-only or the handle is invalid, or to ENOSPC if no space is left on the device. |
|
The header file |
<io.h> |
|
Table 16: _chsize() function information |
|
#include <io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main()
{
int fhdl, result;
char fname[20] = "C:\\data.txt";
/* open a file */
if((fhdl = _open(fname, _O_RDWR | _O_CREAT, _S_IREAD | _S_IWRITE)) != -1)
{
printf("%s file length before running _chsize(): %ld\n", fname, _filelength(fhdl));
/* change the file size */
printf("Executing _chsize(fhdl, 123456)...\n");
if((result = _chsize(fhdl, 123456)) == 0)
printf("%s file size successfully changed!\n", fname);
else
printf("Problem in changing the %s size\n", fname);
/* new size */
printf("%s file length after changing the size: %ld\n", fname, _filelength(fhdl));
/* close the file handle */
_close(fhdl);
}
return 0;
}
The output sample:
|
C:\data.txt file length before running _chsize(): 0 Executing _chsize(fhdl, 123456)... C:\data.txt file size successfully changed! C:\data.txt file length after changing the size: 123456 Press any key to continue |
|
Another example run on VC++ 2005 with SDK installed.
#include <io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <share.h> // _SH_DENYNO
#include <stdio.h>
#include <windows.h> // GetLastError()
int main()
{
int fhdl, result;
/* make sure this file is there, else change accordingly */
char fname[20] = "C:\\data.txt";
/* open a file */
if(_sopen_s( &fhdl, fname, _O_RDWR, _SH_DENYNO, _S_IREAD | _S_IWRITE ) == 0)
{
printf("%s file length before running _chsize(): %ld\n", fname, _filelength(fhdl));
/* change the file size */
printf("Executing _chsize(fhdl, 123456)...\n");
if((result = _chsize(fhdl, 123456)) == 0)
printf("%s file size successfully changed!\n", fname);
else
printf("Problem in changing the %s size. Error %d\n", fname, GetLastError());
/* new size */
printf("%s file length after changing the size: %ld\n", fname, _filelength(fhdl));
/* close the file handle */
_close(fhdl);
}
return 0;
}
A sample output:

|
Function |
Use |
|
_access(), _waccess() |
Check file-permission setting. |
|
_chmod(), _wchmod() |
Change file-permission setting. |
|
_fullpath(), _wfullpath() |
Expand a relative path to its absolute path name. |
|
_get_osfhandle() |
Return operating-system file handle associated with existing stream FILE pointer. |
|
_makepath(), _wmakepath() |
Merge path components into single, full path. |
|
_mktemp(), _wmktemp() |
Create unique filename. |
|
_open_osfhandle() |
Associate C run-time file handle with existing operating-system file handle. |
|
remove(), _wremove() |
Delete file. |
|
rename(), _wrename() |
Rename file. |
|
_splitpath(), _wsplitpath() |
Parse path into components. |
|
_stat(), _stat64(), _stati64(), _wstat(), _wstat64(), _wstati64() |
Get file-status information on named file. |
|
_umask() |
Set default permission mask for new files created by program. |
|
_unlink(), _wunlink() |
Delete file. |
|
Table 17: File handling functions for path and filename |
|
|
Information |
Description |
|
The function |
_chmod(). |
|
The use |
Change the file-permission settings. |
|
The prototype |
int _chmod(const char *filename, int pmode); |
|
Example |
_chmod("test.txt", _S_IREAD); |
|
The parameters |
filename - Name of existing file. pmode - Permission setting for file. |
|
The return value |
These functions return 0 if the permission setting is successfully changed. A return value of –1 indicates that the specified file could not be found, in which case errno is set to ENOENT. |
|
The header file |
<io.h> |
|
Table 18: _chmod() function information |
|
|
Information |
Description |
|
The function |
_fullpath(), _wfullpath(). |
|
The use |
Create an absolute or full path name for the specified relative path name. |
|
The prototype |
char *_fullpath(char *absPath, const char *relPath, size_t maxLength); /* for wide character */ wchar_t *_wfullpath(wchar_t *absPath, const wchar_t *relPath, size_t maxLength); |
|
Example |
char full[_MAX_PATH]; char relPath[20] = "test.txt"; _fullpath(full, relPath, _MAX_PATH); |
|
The parameters |
absPath - Pointer to a buffer containing the absolute or full path name. relPath - Relative path name. maxLength - Maximum length of the absolute path name buffer (absPath). This length is in bytes for _fullpath() but in wide characters (wchar_t) for _wfullpath(). |
|
The return value |
Each of these functions returns a pointer to a buffer containing the absolute path name (absPath). If there is an error (for example, if the value passed in relPath includes a drive letter that is not valid or cannot be found, or if the length of the created absolute path name (absPath) is greater than maxLength) the function returns NULL. |
|
The header file |
<stdlib.h> or <wchar.h> (for _wfullpath()) |
|
Table 19: _fullpath(), _wfullpath() functions information |
|
#include <stdlib.h>
\\machine\shareName\msvcSrc\crt\headerFiles\stdlib.h
_fullpath() automatically handles multibyte-character string arguments as appropriate, recognizing multibyte-character sequences according to the multibyte code page currently in use.
_wfullpath() is a wide-character version of _fullpath(). The string arguments to _wfullpath() are wide-character strings.
_wfullpath() and _fullpath() behave identically except that _wfullpath() does not handle multibyte-character strings.
If the absPath buffer is NULL, _fullpath() calls malloc() to allocate a buffer of size _MAX_PATH and ignores the maxLength argument.
It is the caller's responsibility to de-allocate this buffer (using free) as appropriate. If the relPath argument specifies a disk drive, the current directory of this drive is combined with the path.
The following is a simple program example using the _fullpath() function.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <direct.h>
void DisplayFullPath(char *relPath)
{
/* a buffer */
char full[_MAX_PATH];
if(_fullpath(full, relPath, _MAX_PATH) != NULL)
printf("The full path is: %s\n", full);
else
printf("Invalid path\n");
}
int main()
{
// you need to create those files at those locations else
// change accordingly
DisplayFullPath("test.txt");
DisplayFullPath("\\test.txt");
DisplayFullPath("..\\test.txt");
return 0;
}
The output sample:
The full path is: g:\vcnetprojek\win32prog\test.txt
The full path is: g:\test.txt
The full path is: g:\vcnetprojek\test.txt
Press any key to continue
The following is a sample output run using VC++ Express Edition 2005.

|
Information |
Description |
|
The function |
_splitpath(), _wsplitpath(). |
|
The use |
Break a path name into their components. |
|
The prototype |
void _splitpath( const char *path, char *drive, char *dir, char *fname, char *ext); void _wsplitpath( const wchar_t *path, wchar_t *drive, wchar_t *dir, wchar_t *fname, wchar_t *ext); |
|
Example |
char path_buffer[_MAX_PATH]; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT];
_splitpath(path_buffer, drive, dir, fname, ext); |
|
The parameters |
path - The full path. drive - Optional drive letter, followed by a colon (:). dir - Optional directory path, including trailing slash. Forward slashes (/), backslashes (\), or both may be used. fname - Base filename (no extension). ext - Optional filename extension, including leading period (.). |
|
The return value |
void |
|
The header file |
<stdlib.h> or <wchar.h> for _wsplitpath(). |
|
Table 20: _splitpath(), _wsplitpath() functions information |
|
Each argument is stored in a buffer; the manifest constants _MAX_DRIVE, _MAX_DIR, _MAX_FNAME, and _MAX_EXT (defined in stdlib.h) specify the maximum size necessary for each buffer.
The other arguments point to buffers used to store the path elements. After a call to _splitpath() is executed, these arguments contain empty strings for components not found in path. You can pass a NULL pointer to _splitpath() for any component you don't need.
|
Information |
Description |
|
The function |
_makepath(), _wmakepath(). |
|
The use |
Create a path name from their components. |
|
The prototype |
void _makepath( char *path, const char *drive, const char *dir, const char *fname, const char *ext); /* for wide character */ void _wmakepath( wchar_t *path, const wchar_t *drive, const wchar_t *dir, const wchar_t *fname, const wchar_t *ext); |
|
Example |
char path_buffer[_MAX_PATH]; _makepath(path_buffer, "g", "\\Testdir\\myexample\\", "testfile", "txt"); |
|
The parameters |
path - Full path buffer. _makepath() does not check that path does not exceed _MAX_PATH. drive - Drive letter. dir - Directory path. fname - Filename. ext - File extension. |
|
The return value |
void |
|
The header file |
<stdlib.h> or <wchar.h> for _wmakepath(). |
|
Table 21: _makepath(), _wmakepath() function information |
|
drive - Contains a letter (A, B, and so on) corresponding to the desired drive and an optional trailing colon. _makepath() inserts the colon automatically in the composite path if it is missing. If drive is a null character or an empty string, no drive letter and colon appear in the composite path string.
dir - Contains the path of directories, not including the drive designator or the actual filename. The trailing slash is optional, and either a forward slash (/) or a backslash (\) or both may be used in a single dir argument. If a trailing slash (/ or \) is not specified, it is inserted automatically. If dir is a null character or an empty string, no slash is inserted in the composite path string.
fname - Contains the base filename without any extensions. If fname is NULL or points to an empty string, no filename is inserted in the composite path string.
ext - Contains the actual filename extension, with or without a leading period (.). _makepath() inserts the period automatically if it does not appear in ext. If ext is a null character or an empty string, no period is inserted in the composite path string.
#include <stdlib.h>
#include <stdio.h>
int main()
{
char path_buffer[_MAX_PATH];
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
// change the path accordingly to yours
_makepath(path_buffer, "g", "\\Testdir\\myexample\\", "testfile", "txt");
printf("Path created with _makepath(): %s\n", path_buffer);
_splitpath(path_buffer, drive, dir, fname, ext);
printf("Path extracted with _splitpath():\n");
printf(" Drive: %s\n", drive);
printf(" Dir: %s\n", dir);
printf(" Filename: %s\n", fname);
printf(" Ext: %s\n", ext);
return 0;
}
The output sample:
The full path is: g:\vcnetprojek\win32prog\test.txt
The full path is: g:\test.txt
The full path is: g:\vcnetprojek\test.txt
Press any key to continue
C & C++ Programming Tutorial | C Programming Practice
2003-2009 © Tenouk. All rights reserved.