fstream

发布时间 2023-12-17 21:43:34作者: Elgina

C++ 输入输出流

  1. 对标准设备的输入输出,键盘读入,输出至显示器,称为标准I/O
  2. 对外存文件的输入输出,文件输入数据,数据输出到文件,称为文件I/O
  3. 对内存中指定的空间进行输入输出,称为串I/O
    重点学习fstream(即文件I/O)

get

char c;
c = cin.get(); // 从键盘上获得一个字符,赋值给c   
char c1.c2.c3;
cin.get(c1).get(c2).get(c3); // 从键盘上一次获取三个字符,分别赋给c1,c2,c3   

getline

string str;
getline(cin,str);


ifstream file("poem.txt"); // 输入文件流类,用来读取文件 
string line;
while (getline(file, line)) { // 读取一整行,并将其存入line中  
cout << line << endl;
}
file.close();  

文件流的操作

ifstream ofstream fstream

ifstream _input; // 定义输入文件流 
ofstream _output; // 定义输出文件流 
fstream file; // 定义了一个输入输出流对象file,既可以从文件中读取,也可以往文件中写入     

ofstream outfile("file.dat",ios::out);
ofstream outfile;
outfile.open("file.dat",ios::out);
fstream file("file.dat",ios::in | ios::out);// fstream  多枚举常量形式 用| 并列  fstream ios::in | ios::out 不可省   
outfile.close();
string ID;
getline(cin,ID);
file << ID << endl; // 写入  

getline(file, line);//读取
file >> num;
ios::in //  以输入方式打开文件 
ios::out // 以输出方式找开文件
ios::app // 以输出方式找开文件,写入的数据添加至文件末尾
ios::ate // 打开一个已有的文件,把文件指针移动至文件末尾 
ios::trunc //打开一个文件,若文件已经存在,删除文件中的全部数据,若文件不存在,则建立新文件  

对二进制文件的操作

CSP & NOIP freopen

freopen("name.in","r",stdin);
······
freopen("name.out","w",stdout);