C/C++ 初学简单笔记 ―5― 文件I/O

2014-11-24 08:30:39 · 作者: · 浏览: 0
#include
#include
#include


using namespace std;


/*******************************
文件流处理方式的枚举元素
ios::app 追加文件
*******************************/


// 信息写出到文件中
int Mywrite()
{
ofstream fout;
fout.open("D:\\test.txt",ios::app);
//fout.open("CON"); // 定向到显示屏
if (!fout)
{
cout<<"file open failed"< return -1;
}
fout<<"No problem"< cout<<"No problem"< fout.close();
return 1;
}


// 将文件中的内容读取到程序中
int Myread()
{
ifstream fin;
char str[50];
fin.open("D:\\test.txt");


if (!fin)
{
cout<<"file read failed"< return -1;
}


fin.getline(str,50);
cout<

fin.close();
return 1;


}


// 二进制流读写
int bwrite()
{
ofstream fout;
fout.open("D:\\b.txt",ios::in|ios::binary);
if (!fout)
{
cout<<"file open failed"< return -1;
}
char str[]="Evin_____________";
fout.write(str,strlen(str));
cout< fout.close();
return 1;
}


int bread()
{
ifstream fin;
char str[50];
char str2[50];


fin.open("d:\\b.txt",ios::binary);
if (!fin)
{
cout<<"file read failed"< return -1;
}


fin.read(str,50);
cout< fin.close();
return 1;
}
int main()
{
bwrite();
Myread();
//bread();
return 0;
}


总结
1. 要引入头文件
#include
2. 打开文件, 检查是否正确打开
ofstream fout;
fout.open("D:\\text.txt");
if (!fout) {...}
3. 读/写 信息
fout< fin.getline(info,strlen);
4. 关闭文件
fout.close()/ fin.close()



注:
1. CON 可重定向到屏幕
如: fout.open("CON"); // 将显示到屏幕
2. 有一些文件处理的方式
如: ios::app 表示追加文件

fout.open("D:\\text.txt",ios::app); // 表示存入的信息追加到后面。