深入C语言把文件读入字符串以及将字符串写入文件的解决方法_技术学院_宜昌市隼壹珍商贸有限公司

您好,欢迎访问宜昌市隼壹珍商贸有限公司

400 890 5375
当前位置: 主页 > 新闻动态 > 技术学院

深入C语言把文件读入字符串以及将字符串写入文件的解决方法

发布时间:2026-01-17  |  点击率:

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;

全国统一服务电话

400 890 5375

电子邮箱:879577@qq.com

公司地址:宜昌市西陵区黄河路5号三峡明珠10栋1051室

咨询微信

TEL:13680874598