1.純C實現
複製代碼 代碼如下: 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.利用CFile(MFC基類)
CFile需要包含的標頭檔為Afx.h
開啟檔案的函數原型如下
if(!(fp.Open((LPCTSTR)m_strsendFilePathName,CFile::modeRead)))
有多種模式,常用的有如下:
modeRead
modeWrite
modeReadWrite
modeCreate
檔案類型有兩種:
typeBinary
typeText
讀寫非文字檔一定要用typeBinary
讀取資料的函數原型:
virtual UINTRead(void*lpbuf, UINT nCount);
將檔案讀出:
複製代碼 代碼如下:CFile fp;
if(!(fp.Open((LPCTSTR)m_strsendFilePathName,CFile::modeRead)))
{
return;
}
fp.SeekToEnd();
unsignedint fpLength = fp.GetLength();
char *tmp= new char[fpLength];
fp.SeekToBegin(); //這一句必不可少
if(fp.Read(tmp,fpLength) < 1)
{
fp.Close();
return;
}
// 建立檔案並寫入複製代碼 代碼如下:if(!(fp.Open((LPCTSTR)m_strsendFilePathName,
CFile::modeCreate | CFile::modeWrite |CFile::typeBinary)))
{
return;
}
fp.SeekToBegin();
fp.write(tmp,fpLength);
fp.close;