将输入文件读入字符串以及将字符串写入输出文件

来源:互联网 发布:怎样注册淘宝企业店铺 编辑:程序博客网 时间:2024/06/05 03:33

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 UINT Read(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;

另附一网友方法:

#include <stdio.h>  #include <string.h>  #define MAXLEN 10240  //读取文件filename的内容到dest数组,最多可以读maxlen个字节  //成功返回文件的字节数,失败返回-1  int read_file(const char *filename, char *dest, int maxlen)  {  FILE *file;  int pos, temp, i;  //打开文件  file = fopen(filename, "r");  if( NULL == file )  {  fprintf(stderr, "open %s error\n", filename);  return -1;  }  pos = 0;  //循环读取文件中的内容  for(i=0; i<MAXLEN-1; i++)  {  temp = fgetc(file);  if( EOF == temp )  break;  dest[pos++] = temp;  }  //关闭文件fclose(file);//在数组末尾加0  dest[pos] = 0;  return pos;  }  int main(int argc, char **argv)  {  if( argc != 2 )  {  fprintf(stderr, "Using: ./read <filename>\n");  return -1;  }  char buffer[MAXLEN];  int len = read_file(argv[1], buffer, MAXLEN);  //输出文件内容  printf("len: %d\ncontent: \n%s\n", len, buffer);  return 0;  }  



原创粉丝点击