sfs.close();
}
{
int len;
char* buf;
fstream sfs("test.txt");
sfs.seekg(0,ios::end);//定位到文件末尾
len =sfs.tellg();//返回地址,相当于获取文件的长度
sfs.seekg(0,ios::beg);//获取完之后,将指针提到文件前面
buf = new char[len];
sfs.read(buf,len);//读取文件内容到buf
cout<
sfs.close();
}
}
int main()
{
test();
system("pause");
return 0;
}
例:模拟一个邮件发送端。在DOS命令行下输入XXX.exe mail.txt。相应的信息会写入mail.txt这个文本中。
[cpp]
#include
#include
#include
#include
using namespace std;
int main(int argc,char *argv[])
{
assert(argc>1);
ofstream file;
file.open(argv[1]);
if (!file)
{
cout<<"打开文件失败"<
return 0;
}
int count=0;
file.write((char*)&count,sizeof(int));
string str;
cout<<"——请输入收件人邮箱,以-1结束——"<
{
file<
}
long pos = file.tellp();//获取当前的输出位置
file.seekp(ios_base::beg);//重定位到文件开头
file.write((char*)&count,sizeof(int));//写入收信人信息数目
cout<<"——请输入发件人邮箱——"<
if (cin>>str)
{
file<
cout<<"——请输入主题——"<
{
file<
cout<<"——邮件内容以-1结束——"<
{
file<
file.close();
system("pause");
return 0;
}
例:模拟一个邮件读取端。读取邮件显示的屏幕。
[cpp]
#include
#include
#include
#include
using namespace std;
int main(int argc,char* argv[])
{
assert( argc > 1);
ifstream file;
file.open(argv[1]);
if (!file)
{
cout<<"打开文件失败"<
return 0;
}
string str;
int count = 0;
file.read((char*)&count,sizeof(int));//读取收件人信箱个数
cout<<"——收件人信箱——"<
file>>str;
cout<
cout<<"——发件人信箱——"<
cout<
cout<
{
cout<
file.close();
system("pause");
return 0;
}