CSDN博客

img dgyanyong

用BCB读写文本文件及ini配置文件

发表于2004/9/27 13:13:00  7055人阅读

分类: C++

在头文件中加上#include "IniFiles.hpp"
//读写文本文件
//--写入文本文件
//----------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
char dir[MAX_PATH];
char *tfile = "/nei.txt";
//将程序现在目录所在输入此字符数组
::GetCurrentDirectory(MAX_PATH,dir);
//将现在目录加上指定文件名
strcat(dir,tfile);
//打开文本文件获得handle
HANDLE hFile = ::CreateFile(dir,
                            GENERIC_WRITE,
                            FILE_SHARE_READ,
                            NULL,
                            OPEN_EXISTING,
                            FILE_ATTRIBUTE_NORMAL,
                            NULL);
if (hFile==INVALID_HANDLE_VALUE)
{
  ShowMessage("无法打开新文件");
  return;
}
DWORD BytesWritten;
char theText[MAX_PATH]="你想往文本文件中写入的内容!";
//将theText数组的内容写入程序目录下的nei.txt文件中
if (::WriteFile(hFile,theText,sizeof(theText),&BytesWritten,NULL)||sizeof(theText)==BytesWritten)
{
  ShowMessage("写入文件成功!");
}
::CloseHandle(hFile);
}
//-------------------------------------------------------
//读写ini配置文件实例
//读取ini文件的内容
//-------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
Label2->Caption = "服务器名: ";
Label3->Caption = "数据库名: ";
Label4->Caption = "用户名: ";
Label5->Caption = "密码: ";
//----获取运行程序的目录开始
char dir[MAX_PATH];
char *tfile = "/Config.ini";
//将程序现在目录所在输入此字符数组
::GetCurrentDirectory(MAX_PATH,dir);
//将现在目录加上指定文件名
strcat(dir,tfile);
//----获取运行程序的目录结束
TIniFile  *ini = new TIniFile(dir);
try
{
  Edit1->Text = ini->ReadString("database","servername","缺省值");
  Edit2->Text = ini->ReadString("database","databasename",100);
  Edit3->Text = ini->ReadString("database","UserID",100);
  Edit4->Text = ini->ReadInteger("database","Password",100);
}
catch(...)
{
  MessageBox(Application->Handle,"读取配置文件config.ini失败!","信息提示!",MB_OK+MB_ICONINFORMATION+MB_SYSTEMMODAL);
  delete ini;
}
delete ini;
}
//-----------------------------------------------------
//向ini文件中写入数据
//-----------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
char dir[MAX_PATH];
char *tfile = "/Config.ini";
//将程序现在目录所在输入此字符数组
::GetCurrentDirectory(MAX_PATH,dir);
//将现在目录加上指定文件名
strcat(dir,tfile);
TIniFile  *ini = new TIniFile(dir);
try
  {
    ini->WriteString("DataBase","ServerName",Edit1->Text);
    ini->WriteString("DataBase","DataBaseName",Edit2->Text);
    ini->WriteString("DataBase","UserID",Edit3->Text);
    if ((Trim(Edit4->Text)== "")||(Edit4->Text == NULL))
    {
      ini->WriteInteger("DataBase","Password",NULL);
    }
    else
    {
      ini->WriteInteger("DataBase","Password",StrToInt(Edit4->Text));
    }
    ShowMessage("写入文件成功!");
  }
catch(...)
  {
    Application->MessageBoxA("写入配置文件config.ini失败!",NULL,MB_OK+16);
    delete ini;
    exit(-1);
  }
delete ini;
}
//----------------------------------------------------

阅读全文
0 0

相关文章推荐

img
取 消
img