C++文件操作(一)

来源:互联网 发布:硕士论文淘宝代写 编辑:程序博客网 时间:2024/04/30 17:56
/*一、数据的层次:位 字节 域/记录二、顺序文件:将所有的记录顺序输入文件。一个有限字符构成的顺序字符流。三、C++标准库中:ifstream(文件读取) ofstream(文件写入) fstream(文件读取写入)四、使用/创建文件的基本流程:1. 打开文件 2.读/写文件 3.关闭文件五、建立顺序文件#include <fstream>ofstream outFile("clients.dat",ios::out|ios::binary);ios::out 输出到文件,删除原有内容ios::app 输出到文件,保留原有内容,总是在尾部添加ios::binary 以二进制文件格式打开文件ofstream fout;fout.open("test.out",ios::out|ios::binary);if(!fout){cerr<<"File open error!"<<endl;}六、文件的读写指针(标识文件操作的当前位置,指针在哪里,读写操作就在哪里进行)对于输入文件,有一个读指针对于输出文件,有一个写指针对于输入输出文件,有一个读写指针ofstream fout("a1.out",ios::app);long location = fout.tellp();location = 10L;fout.seekp(location);fout.seekp(location,ios::beg); //从头数locationfout.seekp(location,ios::cur); //从当前位置数locationfout.seekp(location,ios::end); //从尾部数location,location可以是负值ifstream fin("a1.in",ios::in);long location = fin.tellg();location = 10L;fout.seekg(location);fout.seekg(location,ios::beg); //从头数locationfout.seekg(location,ios::cur); //从当前位置数locationfout.seekg(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));二进制文件读写,直接写二进制数据,记事本看未必正确显示关闭文件.close()*/#pragma warning(disable:4996)#include <iostream>#include <fstream>#include <cstring>using namespace std;class CStudent{public:char szName[20];int nScore;};////int main()//{//CStudent s;//ofstream OutFile("StuScores.dat", ios::out | ios::binary);//while (cin >> s.szName >> s.nScore){//if (stricmp(s.szName, "exit") == 0)//break;//OutFile.write((char*) &s, sizeof(s));//}//OutFile.close();//return 0;//}//////int main()//{//CStudent s;//ifstream inFile("StuScores.dat", ios::in | ios::binary);//if (!inFile){//cout << "error" << endl;//return 0;//}//while (inFile.read((char*) &s, sizeof(s))){//cout << s.szName << " " << s.nScore << endl;//}//inFile.close();//return 0;//}//int main(){CStudent s;fstream iofile("StuScores.dat", ios::in | ios::out | ios::binary);if (!iofile){cout << "error" << endl;return 0;}iofile.seekp(2 * sizeof(s), ios::beg);iofile.write("Mike", strlen("Mike") + 1);iofile.seekg(0, ios::beg);while (iofile.read((char*) &s, sizeof(s)))cout << s.szName << " " << s.nScore << endl;iofile.close();return 0;}

0 0