文件操作

C++标准库中: ifstream, ofstream和fstream共3个类
用于文件操作 — 统称为文件流类

文件操作_第1张图片
image.png

C++标准库中: ifstream, ofstream和fstream共3个类
用于文件操作 — 统称为文件流类

#include  // 包含头文件
ofstream outFile(“clients.dat”, ios::out|ios::binary); //打开文件

outFile是自定义的ofstream类的对象
clients.dat 文件名,可以为绝对路径也可以为相对路径
• ios::out 输出到文件, 删除原有内容
• ios::app 输出到文件, 保留原有内容,
总是在尾部添加
• ios::binary 以二进制文件格式打开文件

也可以先创建fout对象,再通过open函数打开

ofstream fout;
 fout.open( “test.out”, ios::out|ios::binary );

判断打开是否成功:

if(!fout) { cerr << “File open error!”<

*cerr 不经过缓冲直接输出

文件读写指针
ofstream fout(“a1.out”, ios::app);
long location = fout.tellp(); //取得写指针的位置
location = 10L;//常数项后面加L
fout.seekp(location); // 将写指针移动到第10个字节处
fout.seekp(location, ios::beg); //从头数location
fout.seekp(location, ios::cur); //从当前位置数location
fout.seekp(location, ios::end); //从尾部数location
location 可以为负值
二进制文件的读写
int x=10;
fout.seekp(20, ios::beg);
fout.write( (const char *)(&x), sizeof(int) );
fin.seekg(0, ios::beg);
fin.read( (char *)(&x), sizeof(int) );
//下面的程序从键盘输入几个学生的姓名的成绩,
//并以二进制, 文件形式存起来
#include 
#include 
#include 
using namespace std;
class CStudent {
 public:
 char szName[20];
 int nScore;
};
二进制文件读写
int main()
{
   CStudent s;
   ofstream OutFile( “c:\\tmp\\students.dat”, ios::out|ios::binary );
   while( cin >> s.szName >> s.nScore ) {
   if( stricmp(s.szName,“exit” ) == 0) //名字为exit则结束
     break;
   OutFile.write( (char *) & s, sizeof(s) );
   }
   OutFile.close();
   return 0;
}

文件写入

int main(){
  CStudent s;
  ifstream inFile("students.dat", ios::in | ios::binary );
  if(!inFile) {
     cout << "error" <

例子: mycopy 程序, 文件拷贝

//用法示例:
//mycopy src.dat dest.dat
//即将 src.dat 拷贝到 dest.dat
//如果 dest.dat 原来就有, 则原来的文件会被覆盖
#include 
#include 
using namespace std;
int main(int argc, char * argv[]){
   if(argc != 3) {
     cout << "File name missing!" << endl;
   return 0;
 }
 ifstream inFile(argv[1], ios::binary|ios::in); //打开文件用于读
   if(! inFile) {
     cout << “Source file open error.” << endl;
   return 0;
 }
 ofstream outFile(argv[2], ios::binary|ios::out); //打开文件用于写
     if(!outFile) {
     cout << “New file open error.” << endl;
   inFile.close(); //打开的文件一定要关闭
   return 0;
 }
   char c;
   while(inFile.get(c)) //每次读取一个字符
     outFile.put(c); //每次写入一个字符
   outFile.close();
   inFile.close();
   return 0;
}

你可能感兴趣的:(文件操作)