c++ builder 文件的操作

c++ builder 文件的操作

一 文件
   1 c 标准文件驱动器,可以支持两种文件类型,二进制文件,和文本文件。c 标准文件是在头文件

stdio.h 中声明。
标准文件类型通过指针来进行存储 FILE * fp;
   2 c++ 流式文件类 fstream,ifstream 和ofstream,分别对应读写,读和写,并支持文本和二进制文

件。
   3 非缓冲文件
二 文件对话框组件
   1 OpenDialog 两种.TXT and .PAS 两种类型的过滤器。
     1) Filter OpenDaalog1->Filter="Text files{*.txt}|*.TXT|Pascal files{*.pas}|*.PAS";
  同一个过滤器中,还可以有多种文件后缀
      OpenDialog1->Filter="Pascal files|*.PAS;*.DPK;*.DPR";
     2) FilterIndex 设置对话框一打开时选中的文件过滤。数值从1开始计算。
     3) InitialDir 设置对话框打开时定位的目录。
     4) Options
       OpenPictureDialog1->Options.Clear();
       OeenPictureDialog1->Options<<ofFileMustExist<<ofHideReadOnly<<ofNoChangeDir;
     5) Title 设置对话框标题中显示的内容。
   2 SaveDialog 组建可以选择并保存文件
   3 OpenPictureDialog 可以选择并打开图形文件。
   4 SavePictureDialog 可以选择并保存图形文件。
三 Win3。1 相关组件
   FileListBox,DirectoryListBox,DriveCombox,FilterComboBox
四 常用文件管理函数
  1 文件函数常用函数
  将一个文件从记录盘上删除,如果不存在或无法删除。则返回False。
  extern PACKAGE bool __fastcall DeleteFile(const AnsiString FileName);
  void __fastcall TFORM1::ButtonClick(TObject *Sender)
  {
      char buffer[256];
      GetWindowsDirectory(buffer,sizeof(buffer));//获取Windows 系统目录
     AnsiString asFileName=FileSearch(Edit1->Text,GetCurrentDir()+AnsiString(";")

+AnsiString(buffer));//在当前目录下和windows系统}//目录下查询文件。 
  if(asFileName.IsEmty()) ShowMessage(AnsiString("Couldn't Found")+Edit1->Text1);
  2 FileSeek
  extern PACKAGE int __fastcall FileSeek(int Handle, int Offset, int Origin);
  extern PACKAGE __int64 __fastcall FileSeek(int Handle, const __int64 Offset, int Origin);

  Description

  Use FileSeek to reposition the read/write point in a file that was opened with FileOpen or

FileCreate. Handle is the file handle that was returned by FileOpen or FileCreate.

  Offset specifies the number of bytes from Origin where the file pointer should be

positioned. Origin is a code with three possible values, denoting the beginning of the file,
  the end of the file, and the current position of the file pointer.

  Origin Action

  0 The file pointer is positioned Offset bytes from the beginning of the file.
  1 The file pointer is positioned Offset bytes from its current position.
  2 The file pointer is positioned Offset bytes from the end of the file.

  If FileSeek is successful, it returns the new position of the file pointer; otherwise, it

returns -1.
   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);
    }
  }
}
 3FileExists
  if(FileExist(SaveDialog1->FileName))
 {
   RenameFile(SaveDialog1->File,SaveDialog1->FileName+".bak");
 }
 iFileHandle=fileCreate(SaveSialog1->FileName);
 for(int i=0;i<Memo2->Lines->String[i].length())
 {
   FileWrite(iFileHandle,Memo2->Lines->String[i].c_str(),length);
 }
 FileClose(iFileHandle);
  4 FileGetAttrs
  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 x(Attrs & faHidden)
  FileSetAttr("MyFile.sys", Attrs & !faHidden);
  A return value of -1 indicates that an error occurred.
  5 FileSetAttrs
  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.
三 目录操作常用函数
  1 CreateDir
     #include <Filectrl.hpp>
   void __fastcall TForm1::Button1Click(TObject *Sender)

   {
      if (!DirectoryExists("c:\\temp"))
      {
            if (!CreateDir("C:\\temp"))
            throw Exception("Cannot create c:\\temp directory.");
      }
   }
   2 ForceDirectories
   ForceDirectories creates a new directory as specified in Dir, which must be a fully-

qualified path name. If the directories given in the path do not yet exist, ForceDirectories

attempts to create them.
   ForceDirectories returns true if it successfully creates all necessary directories, false

if it could not create a needed directory.
   Important
   Do not call ForceDirectories with an empty string. Doing so causes ForceDirectories to

throw an exception. 
   void __fastcall TForm1::Button1Click(TObject *Sender)
   {
         AnsiString Dir = "C:\Apps\Sales\Local";
         if (ForceDirectories(Dir))
         Label1->Caption = Dir + " was created";
   }
   3 GetCurrentDir
   获取当前的目录完整的路径名
   4 RemoveDir
   删除一个存在的目录,目录必须为空
   5 SetCurrentDir设置系统的当前目录
   6 SelectDirectory
   extern PACKAGE bool __fastcall SelectDirectory(constAnsiString Caption, const WideString

Root, AnsiString &Directory);
   Call SelectDirectory to let the user enter a directory name.  
   Use the first syntax to display the Windows directory browser. The Caption parameter

specifies a caption for the dialog. The Root parameter specifies the root directory from

which to browse. The selected directory is returned as the Directory parameter. When using

this syntax,
   SelectDirectory does not change the value of the current directory.
  
   extern PACKAGE bool __fastcall SelectDirectory(AnsiString &Directory, TSelectDirOpts

Options, int HelpCtx);
   enum TSelectDirOpt { sdAllowCreate, sdPerformCreate, sdPrompt };
   typedef Set<TSelectDirOpt, sdAllowCreate, sdPrompt>  TSelectDirOpts;
  
   sdAllowCreate An edit box allows the user to type in the name of a directory that
                        does not exist. This option does not create a directory: the

application
                        must read the name of the selected directory and create it i
                      f desired.
   sdPerformCreate Used only in combination with sdAllowCreate. If the user enters a

directory
                        name that does not exist, the directory selection dialog creates it.
   sdPrompt        Used only in combination with sdAllowCreate. Displays a message box
                       that informs the user when the entered directory does not exist
                       and asks if the directory should be created.
                       If the user chooses OK, the directory is created
                       if the option set includes sdPerformCreate.
                       If the option set does not include sdPerformCreate,
                       the directory is not created:
                the application must read the directory name and create
    #include <FileCtrl.hpp>
    void __fastcall TForm1::Button1Click(TObject *Sender)
   {
      AnsiString Dir = "C:\\Program Files\\MyApp";
      if (SelectDirectory(Dir, TSelectDirOpts() << sdAllowCreate << sdPerformCreate <<

sdPrompt,1000))
      Label1->Caption = Dir;

   }
三 驱动器常用函数
  1 DiskFree 指定驱动器中剩余空间的字节数
  2 DiskSize 驱动器容量
四文件名常用函数
  1 ChangeFileExt
  2 ExtractFileDir
  3 ExtractFileDriver
  4 ExtractFileExt
  5 ExtractFileName
  6 ExtractFilePath
  7 ExtractRelativePath
实例
1
   1
L a b e l 1 目录列表( & D ) : FocusControl: DirectoryListBox1
D i r e c t o r y L i s t B o x 1 D i r L a b e l : L a b e l 6 ;
                                                    FileList: FileListBox1
L a b e l 2 文件列表( & S ) : FocusControl: FileListBox1
F i l e L i s t B o x 1 FileEdit: Edit1
L a b e l 3 驱动器( & R ) : FocusControl: DriveComboBox1
D r i v e C o m b o B o x 1 DirList: DirectoryListBox1
L a b e l 4 文件类型( & F ) : FocusControl: FilterComboBox1
F i l t e r C o m b o B o x 1 FileList: FileListBox1
      Filter: 所有文件 ( * . * ) | * . * |文本文件( * . t x t ) | * . t x t
L a b e l 5 路径名:
L a b e l 6 C : \ S a m p l e s \ S 0 6 B
L a b e l 7 文件名( & N ) : FocusControl: Edit1
E d i t 1
B u t t o n 1 文件长度( & L ) . . . Te x t : * . *
#include<stdio.h>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
FILE* fp;
AnsiString FileFullName;
long size;
AnsiString PropertyMes;
FileFullName=Label2->Caption+"\\"+Edit1->Text;
if(FileExists(FileFullName))
{
  fp=fopen(FileFullName.c_str(),"rt");
  if(fp!=NULL)
  {
    fseek(fp,0L,SEEK_END);
    size=ftell(fp);//get the length of file
    PropertyMes="file is total"+IntToStr(size)+"bytes.";
    MessageDlg(PropertyMes,mtInformation,TMsgDlgButtons() << mbOK, 0);

  }else
  {
      MessageDlg(PropertyMes,mtWarning,TMsgDlgButtons() << mbOK, 0);
  }
  fclose(fp);
 }
}

 2 获取驱动器类型信息
 UINT GetDriveType(
  LPCTSTR lpRootPathName //获取根目录的路径名称
 )
 
表6-5   函数G e t D r i v e Ty p e的返回值及其含义
数 值                             含 义
0                            无法检测驱动器的类型
1                             根目录不存在
D R I V E _ R E M O VA B L E 可移动驱动器
D R I V E _ F I X E D 不可移动驱动器
D R I V E _ R E M O T E 网络驱动器
D R I V E _ C D R O M C D - R O M驱动器
D R I V E _ R A M D I S K 虚拟驱动器

Result=GetDriveType(Edit2->Text.c_str());
3 操作ini 文件



你可能感兴趣的:(c++ builder 文件的操作)