C/C++读写文件相关问题整理

参考:http://hi.baidu.com/sp520hack/blog/item/e4155150e41e686a84352477.html

1.基本读写

2.扩展读写:在末尾添加、逆序读写、文件连接等。

3.格式(二进制、对齐、逐行读写)

4.路径获取

5.字符编码问题(unicode、ascii)

(未完)


头文件:#include <fstream>    //ofstream

追加数据:

首先要指定打开模式

ofstream openFile("x:\\xx.txt",ios::out|ios::in|ios::ate);

文件打开模式:

ios::in     = 0x01, //供读,文件不存在则创建(ifstream默认的打开方式)

ios::out     = 0x02, //供写,文件不存在则创建,若文件已存在则清空原内容(ofstream默认的打开方式)

ios::ate     = 0x04, //文件打开时,指针在文件最后。可改变指针的位置,常和in、out联合使用

ios::app    = 0x08, //供写,文件不存在则创建,若文件已存在则在原文件内容后写入新的内容,指针位置总在最后

ios::trunc     = 0x10, //在读写前先将文件长度截断为0(默认)

ios::nocreate = 0x20, //文件不存在时产生错误,常和in或app联合使用

ios::noreplace  = 0x40, //文件存在时产生错误,常和out联合使用

ios::binary   = 0x80  //二进制格式文件


路径获取:

头文件:#include <Windows.h>//GetModuleFileName
  #include <string>//wstring、string

c++ unicode:
	TCHAR dir[MAX_PATH];
	GetModuleFileName(NULL,dir,MAX_PATH);
	wstring strAppDir = dir;
	wstring strAppDir1=strAppDir;
	wstring::size_type pos = strAppDir1.rfind('\\');
	strAppDir =	strAppDir1.substr(0,pos);
	strAppDir+=_T("\\xxx.txt");

c++ 多字节:
	TCHAR dir[MAX_PATH];
	GetModuleFileName(NULL,dir,MAX_PATH);
	string strAppDir = dir;
	string strAppDir1=strAppDir;
	string::size_type pos = strAppDir1.rfind('\\');
	strAppDir =	strAppDir1.substr(0,pos);
	strAppDir+=_T("\\xxx.txt");

mfc:
	TCHAR path[MAX_PATH];
	GetModuleFileName(NULL,path,MAX_PATH);
	CString strPath = path;
	strPath = strPath.Left( strPath.ReverseFind('\\') );
	strPath+=_T("\\xxx.txt");

c语言(ascii):
	char dir[MAX_PATH];
	int len = GetModuleFileName(NULL,dir,MAX_PATH);
	int pos =len;
	for ( ; pos>=0; --pos)
	{
		if (dir[pos] == '\\')
		break;
	}
	char* dir_ = (char*)calloc(MAX_PATH,sizeof(char));
	memcpy( dir_,dir,pos);
	memcpy( dir_+pos,"\\xxx.txt",strlen("xxx.txt"));
	//...
	free(dir_);
	dir_=NULL;



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值