参考: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");
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;