源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2022-01-24 17:30 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:深入C语言把文件读入字符串以及将字符串写入文件的解决方法
[b]1.纯C实现 [/b]
[u]复制代码[/u] 代码如下:
 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);
[b]2.利用CFile(MFC基类) [/b] CFile需要包含的头文件为Afx.h [b]打开文件的函数原型如下[/b] if(!(fp.Open((LPCTSTR)m_strsendFilePathName,CFile::modeRead))) [b]有多种模式,常用的有如下:[/b] modeRead modeWrite modeReadWrite modeCreate [b]文件类型有两种:[/b] typeBinary typeText 读写非文本文件一定要用typeBinary [b]读取数据的函数原型:[/b] virtual UINTRead(void*lpbuf, UINT nCount); [b]将文件读出: [/b]
[u]复制代码[/u] 代码如下:
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; }
// 新建文件并写入
[u]复制代码[/u] 代码如下:
if(!(fp.Open((LPCTSTR)m_strsendFilePathName,         CFile::modeCreate | CFile::modeWrite |CFile::typeBinary))) {     return; } fp.SeekToBegin(); fp.write(tmp,fpLength); fp.close;
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部