1、c语言的输入输出
c语言常用scanf():从标准输入读取数据,并将其存放至变量、printf():将指定文字/字符串输出到标准输出设备,设定输出宽度和精度;
输入输出缓冲区:
(1)屏蔽低级IO实现
(2)可实现行读取
2、c++的IO流
(1)流,是是对一种有序连续且具有方向性的数据( 其单位可以bit,byte,packet )的抽象描述。为了实现这种流,c++定义了I/O标准库。
(2)c++实现的庞大类库是以ios为基类,其他类是直接或间接派生自ios类的。
(3)cerr、clog标准错误输出流,cin标准输入流,cout标准输出流,新库中要使用这四个功能,必须包含头文件并引入标准命名空间std;
2、文件流对象
文件可根据内容分为二进制文件和文本文件
(1)定义文件流对象
ifstream ifile(输入)
ofstream ofile(输出)
fstream iofile(即可输入又可输出)
(2)使用文件流对象的成员函数打开一个磁盘文件,使得文件流对象和磁盘文件之间建立联系。
(3)用提取和插入运算符对文件进行读写,或用成员函数进行读写
(4)关闭文件
过程演示:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
//利用ofstream类的构造函数创建一个文件输出流对象来打开文件
ofstream fout("c:\\hello.txt");
if (!fout)
{
cout << "文件不能打开" << endl;
}
else//内容输出到磁盘文件
{
fout << "文件以打开" << endl;
}
//关闭文件输出流
fout.close();
//利用ifstream类构造一个文件输入流对象
ifstream fin("c:\\hello.txt");
if (!fin)
{
cout << "文件不能打开" << endl;
}
else
{
char buffer[80];
//从磁盘文件输入到buffeer里并打印
fin >> buffer;
fin.close();
cout << buffer << endl;
}
文件的open操作
ofstream file1;//覆盖写入
if (!file1)
{
cout << "文件不能打开" << endl;
}
else
{
file1.open("c:\\hello.txt");
//file1.open("c:\\test.txt",ios::out|ios::in,0);
//文本文件的写
file1 << "写入" << endl;
file1.close();
}
ifstream file2("c:\\hello.txt");
if (!file2)
{
cout << "文件不能打开" << endl;
}
else
{
char ch[100];
file2 >> ch;
cout << ch << endl;
file2.close();
}
system("pause");
return 0;
}
这里的写入是覆盖写入