输入/输出
I/O类库基本类
ios
istream
—ifstream
—istringstream
ostream
—ofstream
—ostringstream
面向控制台的I/O
- cin(istream的对象)
- cout(ostream的对象)
- cerr和clog(ostream的对象):对应特殊信息(如错误信息),cerr不带缓冲,clog带缓冲
控制台输出操作
1 |
|
控制台输入操作
1 |
|
面向文件的I/O
- 文本方式(text)
- 二进制方式(binary)
文件输出操作
打开文件:创建一个ofstream类的对象
直接方式
ofstream out_file(<文件名> [,<打开方式>]);例如:
ofstream out_file("d:\\myfile.txt",ios::out);间接方式
ofstream out_file;
out_file.open(<文件名> [,<打开方式>]);例如:
out_file.open("d:\\myfile.txt",ios::out);
判断打开是否成功
1
2
3
4
5
6
7if (!out_file.is_open()) //或:out_file.fail()
//或:!out_file
{ ...... //失败处理
}输出数据
1
2
3
4
5
6
7
8
9
10
11
12
13int x=12;
double y=12.3;
......
//以文本方式输出数据
ofstream out_file("d:\\myfile.txt",ios::out);
if (!out_file) exit(-1);
out_file << x << ' ' << y << endl; //输出:12 12.3
或
//以二进制方式输出数据
ofstream out_file("d:\\myfile.dat",ios::out|ios::binary);
if (!out_file) exit(-1);
out_file.write((char *)&x,sizeof(x)); //输出:4个字节
out_file.write((char *)&y,sizeof(y)); //输出:8个字节关闭文件
out_file.close();
目的:把文件内存缓冲区的内容写到磁盘文件中以文本方式输出的文件要以文本方式输入,以二进制方式输出的文件要以二进制方式输入
- Title: 输入/输出
- Author: SyEic_L
- Created at : 2025-04-10 08:31:30
- Updated at : 2025-04-10 08:31:30
- Link: https://blog.syeicl.vip/2025/04/10/输入-输出/
- License: This work is licensed under CC BY-NC-SA 4.0.
推荐阅读
推荐阅读
Comments