C++中对文件 *** 作需要包含头文件
文件类型分为两种:
1.文本文件
2.二进制文件
*** 作文件的三大类:
1.ofstream:写 *** 作
2.ifstream:读 *** 作
3.fstream:读写 *** 作
一、写文件
五大步骤
1.包含头文件
2.创建流对象
3.指定打开方式
4.写内容
5.关闭文件
代码如下:
#include
#include//1.包含头文件
using namespace std;
void test()
{
//2.创建流对象
ofstream ofs;
//3.指定打开方式
ofs.open("test.txt", ios::out);
//4.写内容
ofs << "姓名:张三" << endl;
ofs << "年龄:18" << endl;
ofs << "性别:男" << endl;
//5.关闭文件
ofs.close();
}
int main()
{
test();
return 0;
}
所创建的文件:
二、读文件
五大步骤
1.包含头文件
2.创建流对象
3.打开文件并判断打开是否成功
4.读文件(有多种方法,现在这里写一种,另外几种见下文)
5.关闭文件
代码如下:
#include
#include//1.包含头文件
#include
using namespace std;
void test()
{
//2.创建流对象
ifstream ifs;
//3.打开文件并判断打开是否成功
ifs.open("test.txt", ios::in);
if (!ifs.is_open())//用is_open函数来判断文件是否打开成功(此函数的返回值时boll型)
{
cout << "文件打开失败" << endl;
}
//4.读数据(有多种方法,现在这里写一种,另外几种见下文)
char arr[1024] = { 0 };
while (ifs >> arr)
{
cout << arr << endl;
}
//5.关闭文件
ifs.close();
}
int main()
{
test();
return 0;
}
读文件的另外几种方法:
1.
char arr[1024]={0}; while(ifs.getline(arr,sizeof(arr))) { cout<
2.
string buf; while(getline(ifs,buf)) { cout<
3.
char c; while((c=ifs.get())!=EOF)//EOF end of file 文件结束 { cout<
编者能力有限,请读者批评指正,共同进步!!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)