文件操作

文本文件 写文件
#include<iostream>
using namespace std;
#include<fstream>
void test01()
{
//1.包括头文件fstream
//2.创建流对象
ofstream ofs;
//3.指定打开方式
ofs.open("/.../test.txt",ios::out);
//4.写内容
ofs<<"姓名:张三"<<end1;
ofs<<"性别:男"<<end1;
ofs<<"年龄:18"<<end1;
//5.关闭文件
ofs.close();
}
int main(){
test01();
system("pause");
return 0;
}
读文件
#include<iostream>
using namespace std;
#include<fstream>
void test01()
{
//1.包括头文件fstream
//2.创建流对象
ifstream ifs;
//3.打开方式,并判断是否打开成功
ifs.open("/.../test.txt",ios::in);
if(!ifs.is_open())
{
cout<<"文件打开失败"<<end1;
return;
}
//4.读内容
//第一种
char buf[1024] = {0};
while (ifs >> buf)
{
cout<<buf<<end1;
}
//第二种
char buf[1024] -= { 0 };
while (ifs.getline(buf, sizeof(buf)))
{
cout<<buf<<end1;
}
//5.关闭文件
ifs.close();
}
int main(){
test01();
system("pause");
return 0;
}
接下来我们看下用string来进行读文件
#include<iostream>
using namespace std;
#include<fstream>
#include<string>
void test01()
{
//1.包括头文件fstream
//2.创建流对象
ifstream ifs;
//3.打开方式,并判断是否打开成功
ifs.open("/.../test.txt",ios::in);
if(!ifs.is_open())
{
cout<<"文件打开失败"<<end1;
return;
}
//4.读内容
//第三种
string buf;
while (getline(ifs.buf)
{
cout<<buf<<end1;
}
//5.关闭文件
ifs.close();
}
int main(){
test01();
system("pause");
return 0;
}
第四种是每个字符进行操作
#include<iostream>
using namespace std;
#include<fstream>
#include<string>
void test01()
{
//1.包括头文件fstream
//2.创建流对象
ifstream ifs;
//3.打开方式,并判断是否打开成功
ifs.open("/.../test.txt",ios::in);
if(!ifs.is_open())
{
cout<<"文件打开失败"<<end1;
return;
}
//4.读内容
//第四种
char c;
while ((c = ifs.get()) ! = EOF)
{
cout<<c;
}
//5.关闭文件
ifs.close();
int main(){
test01();
system("pause");
return 0;
}
网友评论