C语言把文件读入字符串以及将字符串写入文件

浅浅的花香味﹌ 2021-07-04 23:02 864阅读 0赞

1.纯C实现

  1. FILE *fp;
  2. if ((fp = fopen("example.txt", "rb")) == NULL)
  3. {
  4. exit(0);
  5. }
  6. fseek(fp, 0, SEEK_END);
  7. int fileLen = ftell(fp);
  8. char *tmp = (char *) malloc(sizeof(char) * fileLen);
  9. fseek(fp, 0, SEEK_SET);
  10. fread(tmp, fileLen, sizeof(char), fp);
  11. fclose(fp);
  12. for(int i = 0; i < fileLen; ++i)
  13. {
  14. printf("%d ", tmp[i]);
  15. }
  16. printf("\n");
  17. if ((fp = fopen("example.txt", "wb")) == NULL)
  18. {
  19. exit(0);
  20. }
  21. rewind(fp);
  22. fwrite(tmp, fileLen, sizeof(char), fp);
  23. fclose(fp);
  24. free(tmp);

2.利用CFile(MFC基类)

CFile需要包含的头文件为Afx.h

打开文件的函数原型如下

  1. if(!(fp.Open((LPCTSTR)m_strsendFilePathName,CFile::modeRead)))

有多种模式,常用的有如下:

  1. modeRead
  2. modeWrite
  3. modeReadWrite
  4. modeCreate

文件类型有两种:

  1. typeBinary
  2. typeText

读写非文本文件一定要用typeBinary

读取数据的函数原型:

  1. virtual UINTRead(void*lpbuf, UINT nCount);

将文件读出:

  1. CFile fp;
  2. if(!(fp.Open((LPCTSTR)m_strsendFilePathName,CFile::modeRead)))
  3. {
  4. return;
  5. }
  6. fp.SeekToEnd();
  7. unsignedint fpLength = fp.GetLength();
  8. char *tmp= new char[fpLength];
  9. fp.SeekToBegin(); //这一句必不可少
  10. if(fp.Read(tmp,fpLength) < 1)
  11. {
  12. fp.Close();
  13. return;
  14. }
  15. // 新建文件并写入
  16. if(!(fp.Open((LPCTSTR)m_strsendFilePathName, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary)))
  17. {
  18. return;
  19. }
  20. fp.SeekToBegin();
  21. fp.write(tmp,fpLength);
  22. fp.close;

发表评论

表情:
评论列表 (有 0 条评论,864人围观)

还没有评论,来说两句吧...

相关阅读