c++读写文件相关的类分别为ifstream(读文件) 和 ofstream(写文件)
ifstream:
一 打开文件:
1.创建ifstream对象时直接打开文件
ifstream( const char* szName, int nMode = ios::in, int nPort = filebuf::openprot);
2.创建一个ifstream对象,之后用成员函数open打开文件
void ifstream::open( const char* szName, int nMode = ios::in, int nProt = filebuf::openprot)
szName:需要打开的文件名/路径
nMode:打开方式 ios::in(从文件读入到内存), ios::nocreate(不创建文件), ios::binary(二进制方式)
nProt: #define _SH_DENYRW 0x10 /* deny read/write mode */
#define _SH_DENYWR 0x20 /* deny write mode */
#define _SH_DENYRD 0x30 /* deny read mode */
#define _SH_DENYNO 0x40 /* deny none mode */
#define _SH_SECURE 0x80 /* secure mode */
二 关闭文件:
使用成员函数 void ifstream::close() 来关闭文件
三 读取文件
1.使用 >> 运算符读取文件内容
int m; ifs >> m; //从文件中读取一个整数
char str[10]; ifs >> str //从文件中读取字符串(可能会越界);
2.成员函数getline( char* str, int num, char c ); //读取文件内容输入到str中,达到num个字节或遇到第三个参数便停止。
3.成员函数get
1) ifstream::get( char& ch ); //从文件中读取一个字符保存在变量ch中,如果到文件尾,返回空字符
2)int ifstream::get(); //从文件中返回一个字符,如果遇到文件尾,返回EOF
3)ifstream::get( char* buf, int num, char delim = '\n' ); //与getline相同
4.成员函数read( char* buf, int num ) //从文件中读取num个字符到buf缓冲中, 如果还未读到num个字符就到了文件尾,可以用成员函数int getcount()来获取实际读取的字符数.
5.成员函数int eof()用来检测是否达到文件尾,如果达到文件尾返回非0值,否则返回0
6.成员函数seekg( streamoff offset(移动的字节数), seek_dir origin(移动的基准位置) )
ifs.seekg( 1024, ios::cur ) 把读指针从当前位置向后移动1024个字节(可为负数)
ofstream:
一 打开文件
与ifstream打开文件相同 打开方式:ios::out(从内存输出到文件) ios::app(追加方式) ios::ate(文件打开后定位到文件尾app包含此类型) ios::binary(二进制)
ios::nocreate(不建立文件,文件不存在是打开失败) ios::noreplace(不覆盖文件,文件存在时打开失败) ios::trunc
二 关闭文件
使用成员函数 void ifstream::close() 来关闭文件
三 写入文件
1.使用 << 运算符写入文件
int m = 10; ofs << m; //把m的值写入文件
2.成员函数 put( char ch ); 向文件中写入一个字符 ofs.put('w');
3.成员函数 write( char* buf, int num ) //从buf指向的缓冲中向文件中写入num个字符
4.成员函数 seekp 移动文件指针
//获得文件大小
int getfilesize(char* FilePath)
{
int iresult;
struct _stat buf;
iresult = _stat( FilePath, &buf);
if( iresult == 0 )
{
return buf.st_size;
}
return 0;
}
2086

被折叠的 条评论
为什么被折叠?



