1,流的概念
1,流的概念
当程序与外部环境进行信息交换时,就存在两个对象,一个是流对象,一个是文件对象。流是一个抽象的概念,可以理解成程序与文件直接数据的流动。
程序操纵流对象, 流和文件发生关系。
读操作,可以理解成从流中提取, 写操作 , 可以理解成向流中插入
2 输出流
1, ostream
cout 标准输出 cerr 标准错误输出,没有缓冲, 发给它的内容立刻被输出
clog 类似于cerr ,但是有缓冲 , 缓冲区满时被输出,这三个都是输出流对象
<< 是重载, 用于把数据转化为字符串的形式, 传送到输出流中
1.cout流
cout是console output的缩写。cout不是c++预定义的关键字,它是ostream流类的对象,在iostream中定义。
cout流在内存中对应开辟了一个缓冲区,用来存放流的数据,当向cout流插入一个endl时,
不论缓冲区是否已满,都立即输出流中所有数据,然后插入一个换行符。
在iostream中只对 << 和
用户自定义的类型数据输入和输出需要自己定义重载。
cout 流通常是传送到显示器输出,但也可以被重定向输出到磁盘文件。
2.cerr流
cerr流是标准错误流,被指定与显示器关联。
不经过缓冲区,直接输出给屏幕。
cout 流通常是传送到显示器输出,但也可以被重定向输出到磁盘文件。
而cerr流中的信息只能在显示器输出。
3.clog流对象
clog流对象也是标准错误流,它是console log的缩写。它的作用和cerr相同,都是在终端显示器上显示出错信息。
它们之间只有一个微小的区别:cerr是不经过缓冲区,直接向显示器上输出有关信息,而clog中的信息存放在缓冲区中,缓冲区满后或遇到endl时向显时器输出。
1,控制输出格式
#include<iostream>
using namespace std;
int main()
{
double data[4]={ 12.1, 12.56, 0.45, 8.90};
for(int i=0; i< 4; i++)
{
cout.width(10);
cout<<data[i]<<endl;
}
return 0;
}
输出结果依右侧对齐
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
double data[3]={12.1, 12.3, 12.4};
for(int i=0; i< 3; i++)
{
cout<<setw(5)<<data[i]<<endl;
}
return 0;
}
2 ofstream
支持磁盘文件输出
ofstream MyFile("scopy.cpp") //在构造这个文件时,该文件是自动打开的
ofstream MyFile; //声明一个静态流对象;
MyFile.open("scopy.cpp");//打开文件,使流和文件建立联系
open 函数, 将流和一个特定的文件联系起来
需要指定模式
put函数, 把一个字符写入输入流中;
write函数, 把内存中的一块写入输入流中
seekp函数和tellp函数, 用于操控文件流内部的指针
close函数, 关闭一个与输出文件流关联的磁盘文件
错误处理函数,
<<插入操作符
#include<fstream>
#include<stdlib.h>
using namespace std;
struct Data{
int year;
int month;
int date;
};
int main()
{
Data da= {12,13,14};
fstream tfile("C:\\Users\\sony\\Desktop\\Scopy.dat");
tfile.write( (char *) &da, sizeof(da) );
tfile.close();
fstream textfile("C:\\Users\\sony\\Desktop\\Scopy1.txt");
textfile<<da.year<<da.month<<da.date<<endl;
textfile.close();
return 0;
}
fstream 中的文件路泾一定要是硬盘上已经存在的,程序不会自动在硬盘上生成
write函数的细节
ifstream
成员函数
open(),get(), getline(), read(), seekg() , tellg(),close()
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream textfile("C:\\Users\\sony\\Desktop\\Scopy1.txt");
if(!textfile)
{
cerr<<"error at the file";
}
char ch;
while( !textfile.eof() )
{
textfile.get(ch);
cout<<ch;
}
return 0;
}
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
ifstream Myfile("C:\\desktop\\de.txt");
ofstream outfile("C:\\desktop\\de1.txt");
string s;
while( getline(myfile,s) )
{
out<<s<<'\n';
}