C语言中的输入输出
C语言中我们使用的输入输出为printf()和scanf()两个函数
printf():将指定的字符串/字符输出到屏幕(标准输出设备)
scanf():将键盘(标准输入设备)读取数据,并将值存放在变量中
输入输出缓冲区
输入输出缓缓冲区可以屏蔽掉低级的I/O的实现,更容易写程序,实现“行”读取行为
流
是对一种有序连续且有方向的数据的抽象描述
C++IO流
cout:进行标准输出,即数据从内存流向控制台
cin:标准输入,即数据从键盘输入程序
cerr:用来进行标准错误的输出
clog:进行日志的输出
cerr,clog,cout本质相同,只是为了区别功能
C++文件IO流
根据文件内容的数据格式分为二进制文件和文本文件
定义文件流对象:
ifstream file(用于输入用)
ofstream file(用于输出用)
fstream file (既输出又输入用)
#include <iostream>
#include <fstream>
#include <assert.h>
using namespace std;
//输入输出流
//ifstream ifile 只用输入
//ofstream ofile 只用输出
//fstream iofile 既输入又输出用
int main()
{
//输出
int ar[] = {12, 23, 34, 45, 56, 78, 89 , 90};
int n = sizeof(ar) / sizeof(ar[0]);
ofstream ofile("Test2.txt", ios::out);//调用构造函数时,打开文件
/*
ofstream ofile;
ofile.open("Test2.txt", ios::out);
*/
if(!ofile)
{
cout << "open faile" << endl;
return 0;
}
for(int i=0; i< n; ++i)
ofile << ar[i] << " ";
ofile << endl;
ofile.close();
int br[10];
ifstream ifile;
ifile.open("Test2.txt", ios::in);
assert(ifile);
for(int i = 0; i < 10; ++i)
ifile >> br[i];
//输入
for(auto& e:br)
{
cout << e << endl;
}
ifile.close();
//二进制输出
int cr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int nn = sizeof(cr) / sizeof(cr[0]);
ofstream ofile1;
ofile1.open("Test3.txt", ios::out|ios::binary);
if(!ofile1)
{
printf("打开失败\n");
return 0;
}
ofile1.write((const char*) cr, sizeof(int)*nn);
ofile1.close();
//二进制读入
/*
C语言的读取方式
int dr[10];
FILE* fp = fopen("Test3.txt", "rb");
assert(fp != NULL);
fread(ar, sizeof(int), 10, fp);
fclose(fp);
*/
int dr[10];
ifstream ifile1;
ifile1.open("Test3.txt", ios::in | ios::binary);
assert(ifile1);
ifile1.read((char*)dr, sizeof(int)*10);
ifile1.close();
return 0;
}