1. Pure C implementation
Copy codeThe Code is as follows: FILE * fp;
If (fp = fopen ("example.txt", "rb") = NULL)
{
Exit (0 );
}
Fseek (fp, 0, SEEK_END );
Int fileLen = ftell (fp );
Char * tmp = (char *) malloc (sizeof (char) * fileLen );
Fseek (fp, 0, SEEK_SET );
Fread (tmp, fileLen, sizeof (char), fp );
Fclose (fp );
For (int I = 0; I <fileLen; ++ I)
{
Printf ("% d", tmp [I]);
}
Printf ("\ n ");
If (fp = fopen ("example.txt", "wb") = NULL)
{
Exit (0 );
}
Rewind (fp );
Fwrite (tmp, fileLen, sizeof (char), fp );
Fclose (fp );
Free (tmp );
2. Use CFile (MFC base class)
The header file to be included in CFile is Afx. h.
The function prototype for opening a file is as follows:
If (! (Fp. Open (LPCTSTR) m_strsendFilePathName, CFile: modeRead )))
There are multiple modes, commonly used as follows:
ModeRead
ModeWrite
ModeReadWrite
ModeCreate
There are two file types:
TypeBinary
TypeText
You must use typeBinary to read and write non-text files.
Function prototype for reading data:
Virtual UINTRead (void * lpbuf, UINT nCount );
Read the file:
Copy codeThe Code is as follows: CFile fp;
If (! (Fp. Open (LPCTSTR) m_strsendFilePathName, CFile: modeRead )))
{
Return;
}
Fp. SeekToEnd ();
Unsignedint fpLength = fp. GetLength ();
Char * tmp = new char [fpLength];
Fp. SeekToBegin (); // This sentence is indispensable
If (fp. Read (tmp, fpLength) <1)
{
Fp. Close ();
Return;
}
// Create a file and write itCopy codeThe Code is as follows: if (! (Fp. Open (LPCTSTR) m_strsendFilePathName,
CFile: modeCreate | CFile: modeWrite | CFile: typeBinary )))
{
Return;
}
Fp. SeekToBegin ();
Fp. write (tmp, fpLength );
Fp. close;