深入C語言把文件讀入字符串以及將字符串寫入文件的解決方法
1.純C實(shí)現(xiàn)
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
打開文件的函數(shù)原型如下
if(!(fp.Open((LPCTSTR)m_strsendFilePathName,CFile::modeRead)))
有多種模式,常用的有如下:
modeRead
modeWrite
modeReadWrite
modeCreate
文件類型有兩種:
typeBinary
typeText
讀寫非文本文件一定要用typeBinary
讀取數(shù)據(jù)的函數(shù)原型:
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;
相關(guān)文章
C++初階之list的模擬實(shí)現(xiàn)過程詳解
在C++中我們經(jīng)常使用STL,那個(gè)在那些我們常用的數(shù)據(jù)結(jié)構(gòu)vector,list的背后,又是如何實(shí)現(xiàn)的呢?這篇文章主要給大家介紹了關(guān)于C++初階之list的模擬實(shí)現(xiàn)的相關(guān)資料,需要的朋友可以參考下2021-08-08
虛函數(shù)被類的構(gòu)造析構(gòu)函數(shù)和成員函數(shù)調(diào)用虛函數(shù)的執(zhí)行過程
虛函數(shù)被類的構(gòu)造析構(gòu)函數(shù)和成員函數(shù)調(diào)用虛函數(shù)的執(zhí)行過程,需要的朋友可以參考下2013-02-02

