描述:
打开文件。
定义:
void open ( const char * filename, ios_base::openmode mode = ios_base::in );
void open ( const char * filename, ios_base::openmode mode = ios_base::out );
参数:
filename- 要打开的文件路径
mode - 文件访问模式
| 文件访问模式常量 | 含义 | 解释 |
|---|---|---|
| ios::in | input | 为输入(读)而打开文件,文件不存在则创建(ifstream默认的打开方式) |
| ios::out | output | 为输出(写)而打开文件,文件不存在则创建,若文件已存在则清空原内容(ofstream默认的打开方式) |
| ios::ate | at end | 文件打开时,指针在文件最后。可改变指针的位置,常和in、out联合使用 |
| ios::app | append | 供写使用,文件不存在则创建,若文件已存在则在原文件内容后写入新的内容,指针位置总在最后 |
| ios::trunc | truncate | 丢弃打开前文件存在的内容(默认) |
| ios::nocreate | 文件不存在时产生错误,常和in或app联合使用 | |
| ios::noreplace | 文件存在时产生错误,常和out联合使用 | |
| ios::binary | 二进制格式文件 |
返回值:
无。可以通过is_open()函数判断文件是否打开成功。
描述:
设置流文件 stream 位置标识符的位置。
定义:
istream& seekg ( streampos pos ); istream& seekg ( streamoff off, ios_base::seekdir dir );
ostream& seekp ( streampos pos ); ostream& seekp ( streamoff off, ios_base::seekdir dir );
参数:
off- 偏移量。整数表示正向偏移,负数表示负向偏移。
dir - 设定从文件的哪里开始偏移,可能取值为:ios_base::beg、 ios_base::cur或 ios_base::end
| 常量 | 描述 |
|---|---|
| ios_base::beg | 文件的开头 |
| ios_base::cur | 文件指针的当前位置 |
| ios_base::end | 文件的末尾 |
返回值:
返回此对象。
描述:
获取指定流 stream 的当前文件位置。
定义:
streampos tellg ( );
streampos tellp ( );
参数:
无
返回值:
返回位置标识符的当前值。如果发生错误,则返回 -1。
描述:
读取文件数据。
函数定义:
istream& read ( char* s, streamsize n );
参数:
s - 指向要读取的数组首地址
n- 要读取的字节大小
返回值:
返回此对象。
描述:
获取上次读取的数据字节数。
函数定义:
streamsize gcount ( ) const;
参数:
无
返回值:
返回上次读取的数据字节数。
描述:
写入文件数据。
函数定义:
ostream& write ( const char* s , streamsize n );
参数:
s - 指向数组中要被写入的首个对象的指针
n - 要被写入的字节数
返回值:
返回此对象。
描述:
关闭文件。
函数定义:
void close ( );
参数:
无
返回值:
无
#include9、示例:写入文件数据#include int main(int argc, char **argv) { //1、打开文件 std::ifstream file; file.open("E:\01-work\temp\微信图片.jpg", std::ios::in | std::ios::binary); if (!file.is_open()) { std::cout << "打开文件失败" << std::endl; return -1; } //2、获取文件大小 file.seekg(0, std::ios::end); //设置文件末尾位置 int nFileSize = file.tellg(); //得到文件长度 file.seekg(0, std::ios::beg); //设置文件起始位置 char* pBuf = new char[nFileSize]; memset(pBuf,0,nFileSize); //3、读取文件数据 file.read(pBuf, nFileSize); if (file.gcount() < nFileSize) { file.close(); delete pBuf; std::cout << "读取文件失败" << std::endl; return -1; } //4、关闭文件 file.close(); delete pBuf; std::cout << "读取文件成功" << std::endl; return 0; }
#include#include int main(int argc, char **argv) { int nFileSize = 1024; //文件大小 char* pBuf = new char[nFileSize]; memset(pBuf, 1, nFileSize); //1、打开文件 std::ofstream file; file.open("E:\01-work\temp\test.txt", std::ios::out | std::ios::binary); if (!file.is_open()) { std::cout << "打开文件失败" << std::endl; return -1; } //2、写入文件数据 file.write(pBuf,nFileSize); if (file.tellp() < nFileSize) { file.close(); delete pBuf; std::cout << "写入文件失败" << std::endl; return -1; } //3、关闭文件 file.close(); delete pBuf; std::cout << "写入文件成功" << std::endl; return 0; }



