当前位置:C++技术网 > 资讯 > 动态插入文本到txt文件

动态插入文本到txt文件

更新时间:2015-12-08 21:05:17浏览次数:1+次

新建对话框工程,将对话框界面设置成下面这样:

为四个编辑框关联变量,分别是m_File,m_Path,m_Goto,m_Text。

为“打开”按钮建立消息响应:

void CGoToFileDlg::OnButopen() 
{
	// TODO: Add your control notification handler code here
	CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
		"All Files(*.TXT)|*.TXT||",AfxGetMainWnd());		//构造文件打开对话框
	if (dlg.DoModal() == IDOK)							//判断是否按下"打开"按钮
	{
		m_Path = dlg.GetPathName();					//获得文件路径
		FILE *pFile = fopen(m_Path,"r+t");				//以读写形式打开文件
		if (pFile)									//判断文件是否被正确打开
		{
			char pchData[1000] = {0};					//定义数据缓冲区
			fread(pchData,sizeof(char),1000,pFile);	//读取数据到缓冲区中
			fclose(pFile);							//关闭文件
			m_File = pchData;
		}
		UpdateData(FALSE);
	}
}
为“插入”按钮建立消息响应:

void CGoToFileDlg::OnButinsert() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
	FILE *pFile = fopen(m_Path,"r+t");				//以读写形式打开文件
	if (pFile)									//判断文件是否被正确打开
	{
		fseek(pFile,m_Goto,SEEK_SET);				//定位文件
		CString str = m_Text + m_File.Right(m_File.GetLength()-m_Goto);//设置字符串
		fputs(str.GetBuffer(0),pFile);	//向文件中写入数据
		fseek(pFile,0,SEEK_SET);					//重新定位文件
		char pchData[1000] = {0};					//定义数据缓冲区
		fread(pchData,sizeof(char),1000,pFile);	//读取数据到缓冲区中
		fclose(pFile);							//关闭文件
		m_File = pchData;
		UpdateData(FALSE);
	}
}
int fseek(FILE *stream, long offset, int fromwhere);函数设置文件指针stream的位置。位置指针指向文
件内部的字节位置,随着文件的读取会移动,文件指针如果不重新赋值将不会改变或指向别的文件。
fseek(pFile,m_Goto,SEEK_SET); //定位文件
将文件指针定位在我们需要插入的位置。


CString str = m_Text + m_File.Right(m_File.GetLength()-m_Goto);//设置字符串

CString::Left(intnCount)
——返回字符串前nCount个字符的字符串
example:
  CString str(_T("Shop,车间"));
  str = str.Left(4);
结果:str="Shop";
 
CString::Right(int nCount)
——返回字符串后nCount个字符的字符串
example:
  CString str(_T("Shop,车间"));
  str = str.Right(2);
结果:str="车间";
 
CString::Find(_T(","))
返回“,”在字符串中的索引值
example:
 CString str(_T("Shop,车间"));
  int idex = str.Find(_T(","));
此时:idex=4;
 
宗:要想获得“,”右侧内容
str = str.Right(str.GetLength()-1-str.Find(_T(",")));
其中:
str.GetLength()=7;
-1排除“,”
-str.Find(_T(","))排除“,”前的所有字


fputs(str.GetBuffer(0),pFile); //向文件中写入数据就是在我们之前定位的位置插入文本。