VC++ in the TXT file to specify the location of the append content method
- 2020-04-02 02:34:27
- OfStack
In this paper, the example of VC++ operation text file method, to achieve the TXT file specified location to insert content. VC++ lovers have a certain learning reference value.
The main function code is as follows:
void CGoToFileDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this);
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
HCURSOR CGoToFileDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CGoToFileDlg::OnButopen()
{
CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
"All Files(*.TXT)|*.TXT||",AfxGetMainWnd());//Construct file open dialog box
if (dlg.DoModal() == IDOK)//Determine whether to press the "open" button
{
m_Path = dlg.GetPathName(); //Get the file path
FILE *pFile = fopen(m_Path,"r+t");//Open the file as a read and write
if (pFile)//Determines if the file is opened correctly
{
char pchData[1000] = {0};//Define data buffer
fread(pchData,sizeof(char),1000,pFile); //Read the data into the buffer
fclose(pFile);//Close the file
m_File = pchData;
}
UpdateData(FALSE);
}
}
void CGoToFileDlg::OnButinsert()
{
UpdateData();
FILE *pFile = fopen(m_Path,"r+t");//Open the file as a read and write
if (pFile)//Determines if the file is opened correctly
{
fseek(pFile,m_Goto,SEEK_SET);//Locate the file
CString str = m_Text + m_File.Right(m_File.GetLength()-m_Goto);//Set string
fputs(str.GetBuffer(0),pFile); //Writes data to a file
fseek(pFile,0,SEEK_SET);// again Locate the file
char pchData[1000] = {0};//Define data buffer
fread(pchData,sizeof(char),1000,pFile); //Read the data into the buffer
fclose(pFile);//Close the file
m_File = pchData;
UpdateData(FALSE);
}
}
The code is fairly well commented and relatively easy to understand. The reader can also further refine the program code to achieve more powerful functions.