文件读写

来源:互联网 发布:淘宝企业店铺的要求 编辑:程序博客网 时间:2024/06/13 08:30
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>//输入输出的类
#include<fstream> //文件输入输出的类,fstream类,它是从iostream类派生的
#include<vector>
using namespace std;


class Email
{
public:
Email() {};
Email(const char *user, const char *mail, const char *key,const int id)
{
this->mID = id;
strcpy(this->mUser, user);
strcpy(this->mMail, mail);
strcpy(this->mKey, key);
}
public:
int mID;
char mUser[64];
char mMail[64];
char mKey[64];
};


void writeFile()
{
//以下两种创建文件流的方式
//1、ofstream outfile("./test.txt",ios::out);//通过默认构造打开文件


ofstream outfile;//2、用ofstream创建文件流对象(所谓流是的是流动的内存,输入输出)
//outfile.open("./test.txt",ios::out,ios::binary); // 二进制方式写入
outfile.open("./test.txt", ios::out);//调用成员方法写的方式打开文件



//1、if (!outfile) //判断文件是否打开成功
if(!(outfile.operator bool()))//2、上面写法和这种写法等价,因为对象类重载了"bool"和"!"
{
cout << "操作失败" << endl;
return;
}
//outfile.clear();//清空文件
outfile.seekp(0,ios::end);//将文件指针移至文件末尾


char buf[1024] = { 0 };
while (1)
{
cin >> buf;
if (buf[0] == '~')break;
outfile << buf << endl;//写入文件直接有左移运算符,对象类重载了"<<" 运算符
//fwrite(buf, sizeof(1024), fp); //c++中写入文件没有fwrite和fread内存块读写
}
outfile.close();//关闭文件
}
void readFile(vector<Email> &mal)
{
//以下两种创建文件流的方式
//1、ofstream outfile("./test.txt",ios::out);//通过默认构造打开文件


ifstream infile;//2、用ofstream创建文件流对象(所谓流是的是流动的内存,输入输出)
//infile.open("./test.txt", ios::in, ios::binary);//二进制方式读取
infile.open("./test.txt", ios::in);//调用成员方法读的方式打开文件




//1、if (!outfile) //判断文件是否打开成功
if (!(infile.operator bool()))//2、上面写法和这种写法等价,因为对象类重载了"bool"和"!"
{
cout << "操作失败" << endl;
return;
}


char buf1[1024] = { 0 };
char buf2[1024] = { 0 };
//while (!infile.eof())//文件读取到末尾返回1,没有读取到末尾返回0
while(1)
{
memset(buf1, 0, 1024);
memset(buf2, 0, 1024);
infile.getline(buf1, 1024);
infile.getline(buf2, 1024);
if (strlen(buf1) == 0)break;


int id = atoi(strtok(buf1, "."));
char *user = strtok(buf1+2, "@");//strtok(字符串分割,参数:1.(要分割的字符串char*),2.(指定以一个字符串来分割))
char *mail = strtok(NULL, "@");//同一行未分割完的字符串第1个参数写NULL
strtok(buf2, ":");
char *key = strtok(NULL, ":");

mal.push_back(Email(user, mail, key, id));
}
infile.close();//关闭文件
}


void writeFile01(const vector<Email> &mal)
{
ofstream outfile("test01.txt", ios::out, ios::binary);
if (!outfile)//文件指针为空返回0
{
cout << "写入失败" << endl;
return;
}
vector<Email>::const_iterator it;
for (it = mal.begin(); it != mal.end(); ++it)
{
outfile << it->mID << "." << it->mUser << "@" << it->mMail << endl << "key:" << it->mKey << endl;
}
outfile.close();//关闭文件
}
void printVector(const vector<Email> &mal)
{
vector<Email>::const_iterator it;
for (it = mal.begin(); it != mal.end(); ++it)
{
cout << it->mID << " " << it->mUser << " " << it->mMail << " " << it->mKey << endl;
}
}
int main()
{
//writeFile();
vector<Email> mal;
readFile(mal);
printVector(mal);
writeFile01(mal);


system("pause");
return 0;
}
0 0
原创粉丝点击