
c++ / примеры
.docChDir procedure
Changes the current directory.
CreateDir
Creates a new directory.
DeleteFile
Deletes a file from disk.
DirectoryExists
Determines whether a specified directory exists.
DiskFree
Returns the number of free bytes on a specified drive.
DiskSize
Returns the size, in bytes, of a specified drive.
File open mode constants
File open mode constants are used to control the access mode to a file or stream.
FileAge
Returns the OS timestamp of a file.
FileClose
Closes a specified file.
FileCreate
Creates a new file.
FileDateToDateTime
Converts an OS timestamp value to TDateTime object.
FileExists
Tests if a specified file exists.
FileGetAttr
Returns the file attributes of FileName.
FileGetDate
Returns an OS timestamp for a specified file.
FileIsReadOnly
Report if file is read-only.
FileOpen
Opens a specified file using a specified access mode.
FileRead
Reads a specified number of bytes from a file.
FileSearch
Searches a specified directory path for a file.
FileSeek
Repositions read/write point.
FileSetAttr
Sets the file attributes of a specified file.
FileSetDate
Sets the OS time stamp for a specified file.
FileSetReadOnly
Sets the file permissions to read-only.
FileWrite
Writes the contents of a buffer to the current position in a file.
FindClose
Releases memory allocated by FindFirst.
FindFirst
Searches for the first instance of a file name with a given set of attributes in a specified directory.
FindNext
Returns the next entry matching the name and attributes specified in a previous call to FindFirst.
ForceDirectories
Creates a new directory, also creating parents as needed.
GetCurrentDir
Returns the name of the current directory.
RemoveDir
Deletes an existing empty directory.
RenameFile
Changes a file name.
SetCurrentDir
Sets the current directory.
The following example creates a directory ‘C:\temp’ if it does not already exist.
#include <Filectrl.hpp>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if (!DirectoryExists("c:\\temp"))
{
if (!CreateDir("C:\\temp"))
throw Exception("Cannot create c:\\temp directory.");
}
}
his example uses a form with a label on it. When the following code executes, it displays a message in the label indicating the number of KB free, and what percentage of the entire disk space that represents.
__int64 AmtFree = DiskFree(0);
__int64 Total = DiskSize(0);
AnsiString S;
S.sprintf("%I64d percent of the space on drive 0 is free: %I64d KB", AmtFree*100/Total, AmtFree/1024 );
Label1->Caption = S;
This example uses a form with a label on it. When the following code executes, it displays a message in the label indicating the number of KB free, and what percentage of the entire disk space that represents.
__int64 AmtFree = DiskFree(0);
__int64 Total = DiskSize(0);
AnsiString S;
S.sprintf("%I64d percent of the space on drive 0 is free: %I64d KB", AmtFree*100/Total, AmtFree/1024 );
Label1->Caption = S;
static const Word fmCreate = 0xffff;
static const Shortint fmOpenRead = 0x0;
static const Shortint fmOpenWrite = 0x1;
static const Shortint fmOpenReadWrite = 0x2;
static const Shortint fmShareCompat = 0x0;
static const Shortint fmShareExclusive = 0x10;
static const Shortint fmShareDenyWrite = 0x20;
static const Shortint fmShareDenyRead = 0x30;
static const Shortint fmShareDenyNone = 0x40;
static const Shortint fmOpenRead = 0x0;
static const Shortint fmOpenWrite = 0x1;
static const Shortint fmOpenReadWrite = 0x2;
static const Shortint fmShareCompat = 0x0;
static const Shortint fmShareExclusive = 0x10;
static const Shortint fmShareDenyWrite = 0x20;
static const Shortint fmShareDenyRead = 0x30;
static const Shortint fmShareDenyNone = 0x40;
Description
The file open mode constants are used when a file or stream is opened to control how it can be shared.
The TFileStream constructor has a Mode parameter that you can set to one of these constants:
Constant Definition
fmCreate If the file exists, open for write access, otherwise, create a new file. Unlike the other constants, which are declared in the SysUtils unit, this constant is declared in classes.h.
fmOpenRead Open for read access only.
fmOpenWrite Open for write access only.
fmOpenReadWrite Open for read and write access.
fmShareCompat Compatible with the way FCBs are opened.
fmShareExclusive Read and write access is denied.
fmShareDenyWrite Write access is denied.
fmShareDenyRead Read access is denied.
fmShareDenyNone Allows full access for others.
The following example uses a button, a string grid, and a Save dialog box on a form. When the button is clicked, the user is prompted for a filename. When the user clicks OK, the contents of the string grid are written to the specified file. Additional information is also written to the file so that it can be read easily with the FileRead function.
#include <dir.h>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
char szFileName[MAXFILE+4];
int iFileHandle;
int iLength;
if (SaveDialog1->Execute())
{
if (FileExists(SaveDialog1->FileName))
{
fnsplit(SaveDialog1->FileName.c_str(), 0, 0, szFileName, 0);
strcat(szFileName, ".BAK");
RenameFile(SaveDialog1->FileName, szFileName);
}
iFileHandle = FileCreate(SaveDialog1->FileName);
// Write out the number of rows and columns in the grid.
FileWrite(iFileHandle, (char*)&(StringGrid1->ColCount), sizeof
(StringGrid1->ColCount));
FileWrite(iFileHandle, (char*)&(StringGrid1->RowCount), sizeof
(StringGrid1->RowCount));
for (int x=0;x<StringGrid1->ColCount;x++)
{
for (int y=0;y<StringGrid1->RowCount;y++)
{
// Write out the length of each string, followed by the string itself.
iLength = StringGrid1->Cells[x][y].Length();
FileWrite(iFileHandle, (char*)&iLength, sizeof(iLength));
FileWrite(iFileHandle, StringGrid1->Cells[x][y].c_str(), StringGrid1->Cells[x][y].Length());
}
}
FileClose(iFileHandle);
}
}
extern PACKAGE int __fastcall FileGetAttr(const AnsiString FileName);
Description
FileGetAttr returns the attributes of the file as a string of bits. This value is the same as the Attr field of a TSearchRec struct. Check for individual attributes with code such as the following:
int Attrs = FileGetAttr("MyFile.sys");
if (Attrs & faHidden)
FileSetAttr("MyFile.sys", Attrs & !faHidden);
A return value of -1 indicates that an error occurred.
Note: See TSearchRec for a description of the individual attribute constants.
extern PACKAGE int __fastcall FileGetAttr(const AnsiString FileName);
Description
FileGetAttr returns the attributes of the file as a string of bits. This value is the same as the Attr field of a TSearchRec struct. Check for individual attributes with code such as the following:
int Attrs = FileGetAttr("MyFile.sys");
if (Attrs & faHidden)
FileSetAttr("MyFile.sys", Attrs & !faHidden);
A return value of -1 indicates that an error occurred.
Note: See TSearchRec for a description of the individual attribute constants.
extern PACKAGE int __fastcall FileGetAttr(const AnsiString FileName);
Description
FileGetAttr returns the attributes of the file as a string of bits. This value is the same as the Attr field of a TSearchRec struct. Check for individual attributes with code such as the following:
int Attrs = FileGetAttr("MyFile.sys");
if (Attrs & faHidden)
FileSetAttr("MyFile.sys", Attrs & !faHidden);
A return value of -1 indicates that an error occurred.
Note: See TSearchRec for a description of the individual attribute constants.
extern PACKAGE bool__fastcall FileIsReadOnly(const AnsiString FileName);
Description
FileIsReadOnly returns true if FileName can be found and opened, but the current process does not have permission to write to it.
The following example uses a button, a string grid, and an Open dialog box on a form. When the button is clicked, the user is prompted for a filename. When the user clicks OK, the specified file is opened, read into a buffer, and closed. Then the buffer is displayed in two columns of the string grid. The first column contains the character values in the buffer. The second column contains the numeric values of the characters in the buffer.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int iFileHandle;
int iFileLength;
int iBytesRead;
char *pszBuffer;
if (OpenDialog1->Execute())
{
try
{
iFileHandle = FileOpen(OpenDialog1->FileName, fmOpenRead);
iFileLength = FileSeek(iFileHandle,0,2);
FileSeek(iFileHandle,0,0);
pszBuffer = newchar[iFileLength+1];
iBytesRead = FileRead(iFileHandle, pszBuffer, iFileLength);
FileClose(iFileHandle);
for (int i=0;i<iBytesRead;i++)
{
StringGrid1->RowCount += 1;
StringGrid1->Cells[1][i+1] = pszBuffer[i];
StringGrid1->Cells[2][i+1] = IntToStr((int)pszBuffer[i]);
}
delete [] pszBuffer;
}
catch(...)
{
Application->MessageBox("Can't perform one of the following file operations: Open, Seek, Read, Close.", "File Error", IDOK);
}
}
}
The following example uses an edit control and a button on a form. When the button is clicked, the current directory and the Windows directory are searched for the filename specified in the edit control. A message box indicates whether the file is found.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
char buffer[256];
GetWindowsDirectory(buffer, sizeof(buffer));
AnsiString asFileName = FileSearch(Edit1->Text, GetCurrentDir() + AnsiString(";") + AnsiString(buffer));
if (asFileName.IsEmpty())
ShowMessage(AnsiString("Couldn't find ") + Edit1->Text + ".");
else
ShowMessage(AnsiString("Found ") + asFileName + ".");
}
extern PACKAGE int __fastcall FileSetAttr(const AnsiString FileName, int Attr);
Description
FileSetAttr sets the file attributes of the file given by FileName to the value given by Attr. The value of Attr is formed by combining the appropriate file attribute constants, as in the following:
FileSetAttr("MyFile.sys", faReadOnly | faSysFile);
FileSetAttr returns zero if the function was successful. Otherwise the return value is an error code.
FileSetDate sets the OS timestamp of the specified file to the value given by Age. The DateTimeToFileDate function can be used to convert a TDateTime object to a OS timestamp.
Handle is the Windows file handle of the file to alter.
FileName is the name of the file to alter.
Age is the timestamp to apply to the specified file.
The return value is zero if the function was successful. Otherwise the return value is an error code.
The following example uses a button, a string grid, and a Save dialog box on a form. When the button is clicked, the user is prompted for a filename. When the user clicks OK, the contents of the string grid are written to the specified file. Additional information is also written to the file so that it can be read easily with the FileRead function.
#include <dir.h>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
char szFileName[MAXFILE+4];
int iFileHandle;
int iLength;
if (SaveDialog1->Execute())
{
if (FileExists(SaveDialog1->FileName))
{
fnsplit(SaveDialog1->FileName.c_str(), 0, 0, szFileName, 0);
strcat(szFileName, ".BAK");
RenameFile(SaveDialog1->FileName, szFileName);
}
iFileHandle = FileCreate(SaveDialog1->FileName);
// Write out the number of rows and columns in the grid.
FileWrite(iFileHandle, (char*)&(StringGrid1->ColCount), sizeof
(StringGrid1->ColCount));
FileWrite(iFileHandle, (char*)&(StringGrid1->RowCount), sizeof
(StringGrid1->RowCount));
for (int x=0;x<StringGrid1->ColCount;x++)
{
for (int y=0;y<StringGrid1->RowCount;y++)
{
// Write out the length of each string, followed by the string itself.
iLength = StringGrid1->Cells[x][y].Length();
FileWrite(iFileHandle, (char*)&iLength, sizeof(iLength));
FileWrite(iFileHandle, StringGrid1->Cells[x][y].c_str(), StringGrid1->Cells[x][y].Length());
}
}
FileClose(iFileHandle);
}
}
The following example uses an edit control, a button, a string grid, and seven check boxes. The check boxes correspond to the seven possible file attributes. When the button is clicked, the path specified in the edit control is searched for files matching the checked file attributes. The names and sizes of the matching files are inserted into the string grid.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
TSearchRec sr;
int iAttributes = 0;
StringGrid1->RowCount = 1;
iAttributes |= faReadOnly * CheckBox1->Checked;
iAttributes |= faHidden * CheckBox2->Checked;
iAttributes |= faSysFile * CheckBox3->Checked;
iAttributes |= faVolumeID * CheckBox4->Checked;
iAttributes |= faDirectory * CheckBox5->Checked;
iAttributes |= faArchive * CheckBox6->Checked;
iAttributes |= faAnyFile * CheckBox7->Checked;
StringGrid1->RowCount = 0;
if (FindFirst(Edit1->Text, iAttributes, sr) == 0)
{
do
{
if ((sr.Attr & iAttributes) == sr.Attr)
{
StringGrid1->RowCount = StringGrid1->RowCount + 1;
StringGrid1->Cells[1][StringGrid1->RowCount-1] = sr.Name;
StringGrid1->Cells[2][StringGrid1->RowCount-1] = IntToStr(sr.Size);
}
} while (FindNext(sr) == 0);
FindClose(sr);
}
}
The following example uses an edit control, a button, a string grid, and seven check boxes. The check boxes correspond to the seven possible file attributes. When the button is clicked, the path specified in the edit control is searched for files matching the checked file attributes. The names and sizes of the matching files are inserted into the string grid.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
TSearchRec sr;
int iAttributes = 0;
StringGrid1->RowCount = 1;
iAttributes |= faReadOnly * CheckBox1->Checked;
iAttributes |= faHidden * CheckBox2->Checked;
iAttributes |= faSysFile * CheckBox3->Checked;
iAttributes |= faVolumeID * CheckBox4->Checked;
iAttributes |= faDirectory * CheckBox5->Checked;
iAttributes |= faArchive * CheckBox6->Checked;
iAttributes |= faAnyFile * CheckBox7->Checked;
StringGrid1->RowCount = 0;
if (FindFirst(Edit1->Text, iAttributes, sr) == 0)
{
do
{
if ((sr.Attr & iAttributes) == sr.Attr)
{
StringGrid1->RowCount = StringGrid1->RowCount + 1;
StringGrid1->Cells[1][StringGrid1->RowCount-1] = sr.Name;
StringGrid1->Cells[2][StringGrid1->RowCount-1] = IntToStr(sr.Size);
}
} while (FindNext(sr) == 0);
FindClose(sr);
}
}
This example uses a label and a button on a form. When the user clicks the button, all the directories along the specified path that don't exist are created. The results are reported in the caption of the label:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
AnsiString Dir = "C:\Apps\Sales\Local";
if (ForceDirectories(Dir))
Label1->Caption = Dir + " was created";
}
Deletes an existing empty directory.
Unit
SysUtils
Category
file management routines
extern PACKAGE bool __fastcall RemoveDir(const AnsiString Dir);
Description
Call RemoveDir to remove the directory specified by the Dir parameter. The return value is true if a new directory was successfully deleted, false if an error occurred. The directory must be empty before it can be successfully deleted.
he following example uses a button, a string grid, and a Save dialog box on a form. When the button is clicked, the user is prompted for a filename. When the user clicks OK, the contents of the string grid are written to the specified file. Additional information is also written to the file so that it can be read easily with the FileRead function.
#include <dir.h>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
char szFileName[MAXFILE+4];
int iFileHandle;
int iLength;
if (SaveDialog1->Execute())
{
if (FileExists(SaveDialog1->FileName))
{
fnsplit(SaveDialog1->FileName.c_str(), 0, 0, szFileName, 0);
strcat(szFileName, ".BAK");
RenameFile(SaveDialog1->FileName, szFileName);
}
iFileHandle = FileCreate(SaveDialog1->FileName);
// Write out the number of rows and columns in the grid.
FileWrite(iFileHandle, (char*)&(StringGrid1->ColCount), sizeof
(StringGrid1->ColCount));
FileWrite(iFileHandle, (char*)&(StringGrid1->RowCount), sizeof
(StringGrid1->RowCount));
for (int x=0;x<StringGrid1->ColCount;x++)
{
for (int y=0;y<StringGrid1->RowCount;y++)
{
// Write out the length of each string, followed by the string itself.
iLength = StringGrid1->Cells[x][y].Length();
FileWrite(iFileHandle, (char*)&iLength, sizeof(iLength));
FileWrite(iFileHandle, StringGrid1->Cells[x][y].c_str(), StringGrid1->Cells[x][y].Length());
}
}
FileClose(iFileHandle);
}
}
Sets the current directory.
Unit
SysUtils
Category
file management routines
extern PACKAGE bool __fastcall SetCurrentDir(const AnsiString Dir);
Description
The SetCurrentDir function sets the current directory. The return value is true if the current directory was successfully changed, or false if an error occurred.