C++ 文件输入/输出(2)
2017-11-07 19:04
183 查看
顺序访问文件
文本文件和二进制文件进行读/写操作。
1.文本文件读/写操作
例如: 向文件mufile.text写入一个整数,一个浮点数以及一个字符串。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream out("myflie.txt");
//创建流对象并打开文件
if(!out)
//判断文件是否成功打开
{
cout<<"can't open file myfile.txt \n";
renturn 1;
}
out <<123<<" "<<1<<" "<<"They are boys"<<endl;
//向文件写入数据
out.close();
//关闭文件
return 0;
}
读入数据:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int a;
double b;
char ch,str1[20],str2[20];
ifstream in("myfie.txt");
//创建流对象并打开文件
if(!in is_open)
//判断文件是否成功打开
{
cout<<"can't open file!\n"<<endl;
return 1;
}
in>>a>>b>>ch>>str1;
cout<<a<<endl;
cout<<b<<endl:
cout<<ch<<endl;
cout<<str1<<endl;
in.getline(str2.20);
cout<<str2<<endl;
return 0;
}
二进制文件的读/写
如果在代开文件时指定了模式 iOS::binary, 就以二进制方式打开了文件。通常有两种方法可以从文件读取或者写入二进制数据: 一种是使用函数get()从文件中读取一个字符,使用函数 put()向文件中写入一个字符;另一种是使用流库中的数据块输入和输出函数read()和write();(我们通常是使用read()跟write())
:
istream &istream::read(char *buff ,streamsize num);
ostream &ostream::write(char *buf,streamsize num);
文本文件和二进制文件进行读/写操作。
1.文本文件读/写操作
例如: 向文件mufile.text写入一个整数,一个浮点数以及一个字符串。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream out("myflie.txt");
//创建流对象并打开文件
if(!out)
//判断文件是否成功打开
{
cout<<"can't open file myfile.txt \n";
renturn 1;
}
out <<123<<" "<<1<<" "<<"They are boys"<<endl;
//向文件写入数据
out.close();
//关闭文件
return 0;
}
读入数据:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int a;
double b;
char ch,str1[20],str2[20];
ifstream in("myfie.txt");
//创建流对象并打开文件
if(!in is_open)
//判断文件是否成功打开
{
cout<<"can't open file!\n"<<endl;
return 1;
}
in>>a>>b>>ch>>str1;
cout<<a<<endl;
cout<<b<<endl:
cout<<ch<<endl;
cout<<str1<<endl;
in.getline(str2.20);
cout<<str2<<endl;
return 0;
}
二进制文件的读/写
如果在代开文件时指定了模式 iOS::binary, 就以二进制方式打开了文件。通常有两种方法可以从文件读取或者写入二进制数据: 一种是使用函数get()从文件中读取一个字符,使用函数 put()向文件中写入一个字符;另一种是使用流库中的数据块输入和输出函数read()和write();(我们通常是使用read()跟write())
:
istream &istream::read(char *buff ,streamsize num);
ostream &ostream::write(char *buf,streamsize num);
相关文章推荐
- C++学习笔记——4.输入、输出和文件
- C++学习笔记:文件输入和输出
- C++ Primer Plus(十七)——输入、输出和文件
- C++ basic 02: 文件输入和输出
- C++中的文件输入/输出(4):检测输入/输出的状态标志
- C++中的文件输入/输出ios:xx eat Processing(zz)
- C++中的文件输入/输出
- 【读书笔记:C++ primer plus 第六版 中文版】第17章 输入、输出和文件
- C++ 程序设计入门(下)- 第 7 单元 - 文件输入和输出
- 《C++ Primer Plus(第六版)》(42)(第十七章 输入、输出和文件 编程练习和答案2)
- freopen - C/C++文件输入输出利器
- C++中的文件输入/输出
- C与C++文件输入输出效率简单研究 上篇
- C++中的文件输入/输出(5):二进制文件的处理
- c++文件的输入输出
- C++中的文件的输入输出函数应用实例
- 你好,C++(5)如何输出数据到屏幕、从屏幕输入数据与读写文件?
- C++中的文件输入/输出
- C++中的文件输入/输出
- C++中的文件输入/输出(1):你的第一个程序