深入C語言把檔案讀入字串以及將字串寫入檔案的解決方案

來源:互聯網
上載者:User

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;

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.