您的位置:首页 > 编程语言 > C语言/C++

五、c++简单的文件操作

2017-11-20 21:54 627 查看
一、基本操作

1.定义输入文件:

ifstream ifile;

定义输出文件:

ofstream ofile;

2.打开文件:

ifile.open("这里是路径比如d:\\test.txt");

ofile.open("路径");

3.对文件内容读写:就用>> << getline get就可以,cin用ifile代替,cout用ofile代替

4.关闭文件:

ifile.close(); ofile.close();

举个例子:写入一下话进文件

#include <fstream>//注意头文件

using namespace std;

int main()
{
ofstream ofile;
ofile.open("myfile.txt");
ofile<<"这是一个测试的文本"<<endl;
for(int i=0;i<100;i++){
ofile<<i<<endl;
}
ofile.close();
return 0;
}

这时如果有这个名字的就在里面改,没有就新建了,而且每次执行文件内容是刷新,不是在后头追加。
在来一个读的例子:要是没有我路径指定的文件,就输出空了
#include <fstream>//注意头文件
#include <iostream>
using namespace std;

int main()
{
char ch[255];
ifstream ifile;
ifile.open("myfile.txt");
ifile.getline(ch,255);
cout<<ch<<endl;
ifile.close();
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: