class CStudent { char szName[20]; //假设学生姓名不超过19个字符,以 '\0' 结尾 char szId[l0]; //假设学号为9位,以 '\0' 结尾 int age; //年龄 };如果用文本文件存储学生的信息,文件可能是如下样子:
ostream & write(char* buffer, int count);
该成员函数将内存中 buffer 所指向的 count 个字节的内容写入文件,返回值是对函数所作用的对象的引用,如 obj.write(...) 的返回值就是对 obj 的引用。#include <iostream> #include <fstream> using namespace std; class CStudent { public: char szName[20]; int age; }; int main() { CStudent s; ofstream outFile("students.dat", ios::out | ios::binary); while (cin >> s.szName >> s.age) outFile.write((char*)&s, sizeof(s)); outFile.close(); return 0; }输入:
Tom烫烫烫烫烫烫烫烫 Jack烫烫烫烫烫烫烫? Jane烫烫烫烫烫烫烫?
istream & read(char* buffer, int count);
该成员函数从文件中读取 count 个字节的内容,存放到 buffer 所指向的内存缓冲区中,返回值是对函数所作用的对象的引用。int gcount();
read 成员函数从文件读指针指向的位置开始读取若干字节。文件读指针是 ifstream 或 fstream 对象内部维护的一个变量。文件刚打开时,文件读指针指向文件的开头(如果以ios::app 方式打开,则指向文件末尾),用 read 函数读取 n 个字节,读指针指向的位置就向后移动 n 个字节。因此,打开一个文件后连续调用 read 函数,就能将整个文件的内容读取出来。#include <iostream> #include <fstream> using namespace std; class CStudent { public: char szName[20]; int age; }; int main() { CStudent s; ifstream inFile("students.dat",ios::in|ios::binary); //二进制读方式打开 if(!inFile) { cout << "error" <<endl; return 0; } while(inFile.read((char *)&s, sizeof(s))) { //一直读到文件结束 int readedBytes = inFile.gcount(); //看刚才读了多少字节 cout << s.szName << " " << s.age << endl; } inFile.close(); return 0; }程序的输出结果是:
mycopy 源文件名 目标文件名
就能将源文件复制到目标文件。例如:mycopy src.dat dest.dat
即将 src.dat 复制到 dest.dat。如果 dest.dat 原本就存在,则原来的文件会被覆盖。#include <iostream> #include <fstream> using namespace std; int main(int argc, char* argv[]) { if (argc != 3) { cout << "File name missing!" << endl; return 0; } ifstream inFile(argv[l], 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; }文件存放于磁盘中,磁盘的访问速度远远低于内存。如果每次读一个字节或写一个字节都要访问磁盘,那么文件的读写速度就会慢得不可忍受。因此,操作系统在接收到读文件的请求时,哪怕只要读一个字节,也会把一片数据(通常至少是 512 个字节,因为磁盘的一个扇区是 512 B)都读取到一个操作系统自行管理的内存缓冲区中,当要读下一个字节时,就不需要访问磁盘,直接从该缓冲区中读取就可以了。
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有