请问怎么读写*ini文件,具体见内

请教如何读写*.ini文件,具体见内
很不好意思,今天我没分了,最后的10分,呵呵!!!

我写在写远程数据库时有时连接会断开,在没回复前
我在*ini文件里每次把数组int   num[3],和一个CSting   Name写进去,连接恢复后再
读出来写进库.

请问   如何把   数据写进*ini   文件,并读出来再对应放进   num和Name里


------解决方案--------------------
不用MFC
int num[3] = { 1, 2, 3 };
CString str( "test " );
FILE* f = NULL;

if( ( f = fopen( "test.txt ", "wb " ) ) == NULL )
exit(1);

fprintf( f, "%d %d %d %s ", num[0], num[1], num[2], (LPCTSTR)str );

fclose( f );

if( ( f = fopen( "test.txt ", "rb " ) ) == NULL )
exit(1);

fscanf( f, "%d %d %d %s ", &num[0], &num[1], &num[2], str.GetBuffer(100) );
str.ReleaseBuffer();

fclose( f );
------解决方案--------------------
读写ini可以用下面函数:
WritePrivateProfileSection
WritePrivateProfileString
WritePrivateProfileStruct
GetPrivateProfileInt
GetPrivateProfileSection
GetPrivateProfileSectionNames
GetPrivateProfileString
GetPrivateProfileStruct



------解决方案--------------------
Windows操作系统专门为此提供了6个API函数来对配置设置文件进行读、写:

  GetPrivateProfileInt() 从私有初始化文件获取整型数值
  GetPrivateProfileString() 从私有初始化文件获取字符串型值
  GetProfileInt 从win.ini 获取整数值
  GetProfileString 从win.ini 获取字符串值
  WritePrivateProfileString 写字符串到私有初始化文件
  WriteProfileString 写字符串到win.ini

我们可以把视图类的:OnInitialUpdate() 函数作为程序启动时读取配置文件的入口,配置文件的存储格式如下:

[SECTION 1]
XPos=300
YPos=200

[SECTION 2]
Text=Hello

  仅有两个节,XPos和YPos标明了待显示信息的坐标,而待显示的信息存储在第二节的Text项中,用读取访问私有配置设置文件的API函数将其分别读入到变量m_nXPos,m_nYPos和m_strText中,并通过Invalidate()调用OnDraw()函数,在其内用TextOut函数将该信息在读取的坐标位置显示出来:

m_nXPos=GetPrivateProfileInt( "SECTION 1 ", //节名
"XPos ", //项名
0, //没找到此项时的缺省返回值
"C:\\test\\debug\\test.ini "); //配置文件的准确路径

m_nYPos=GetPrivateProfileInt( "SECTION 1 ", "YPos ",0,exeFullPath);
char buf[256];
len=GetPrivateProfileString( "SECTION 2 ", //节名
"Text ", //项名
"No Text ", //没找到此项时的返回值
buf, //目标缓冲区地址
256, //目标缓冲区长度
"C:\\test\\debug\\test.ini "); //配置文件的准确路径
for(int i=0;i <len;i++)
{
 CString str;
 str.Format( "%c ",buf[i]);
 m_strText+=str;
}
Invalidate();

  一般配置文件是和应用程序存放在同一个目录中的如果用 "C:\\test\\debug\\test.ini "的绝对路径进行设置就会出现路径改变后找不到配置文件的问题,所以应动态搜寻配置文件的存放地址:

TCHAR exeFullPath[MAX_PATH]; // MAX_PATH在API中有定义,为128
int len=GetModuleFileName(NULL,
exeFullPath, //应用程序的全路径存放地址
MAX_PATH);
CString path= "\\test.ini "; //配置文件名
::strcpy(exeFullPath+len-13,path); //组合出配置文件的全路径

  写配置文件也基本类似,只是需要把数值类型的变量格式化成字符串再行存储:

str.Format( "%d ",m_nXPos);
WritePrivateProfileString( "SECTION 1 ", "XPos ",str,exeFullPath);
str.Format( "%d ",m_nYPos);
WritePrivateProfileString( "SECTION 1 ", "YPos ",str,exeFullPath);
WritePrivateProfileString( "SECTION 2 ", "Text ",m_strText,exeFullPath);

  我们一定遇到过这样的程序:在执行过一遍以后,重启系统会自动加载该程序,其实除了在启动菜单和注册表添加信息外,也可以用WriteProfileString()函数向win.ini的 "windows "节的 "run "项目添加应用程序的全路径来实现,这要比其它两种方法简便的多,而且也比较安全。


二.将信息从INI文件中读入程序中的变量.

  1.所用的WINAPI函数原型为:

DWORD GetPrivateProfileString(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,