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

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;  
}  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值