STL文件操作简介

我们经常整些命令台程序,啥cout<<, cin>>之类的.而实际项目中基本上不会要你用cout啥的在屏幕上输出.而在硬盘上读写文件操作倒很多.

假如没用到MFC或者win API咋去读写文件呢.STL中提供了一些类可以让你很方便的读写文件.比较常见有有三个:

fstream :可以写也可以读文件

ofstream: 只能写文件

ifstream:只能读文件

 

写文件

#include <iostream>

#include <string>

#include <fstream>  //记得引用该头文件

using namespace std;

 

int main()

{

 //用fstream来写文件

  string filePath = "D:\\arwen.txt";

  fstream writeFile;

  writeFile.open( filePath, ios::out);  //打开文件,如果文件不存在则创建该文件.

  writeFile<<"hello arwen."<<endl;  //往文件中写入内容,如果打开的文件中之前有内容会被覆盖.如果只想在原有内容上添加内容则要这样打开文件

                                                  //writeFile.open(filePath, ios::out | ios::app);

  fstream.close();

 

//用ofstream来写文件

 string filePath = "D:\\tmp.txt";

 ofstream fileWriteOnly;

 fileWriteOnly.open( filePath, ios::out);

 fileWriteOnly << "i am temp file"<<endl;

fileWriteOnly.close();

 

读文件

//用fstream读文件

string filePath = "D:\\arwen.txt";

fstream readFile;

readFile.open( filePath, ios::in);

char ch;

while( readFile.get(ch) )

       cout<<ch;

readFile.close();

 

//用ifstream读文件

string filePath = "D:\\tmp.txt";

ofstream fileReadOnly;

fileReadOnly.open( filePath, ios::in);

while( fileReadOnly.get(ch) )

cout<<ch;

 

fileReadOnly.close();

 

return 0;

}

 

上面读文件是一次读一个char,也可以一次读一行.

例如

string filePath = "D:\\tmp.txt";

ofstream fileReadOnly;

fileReadOnly.open( filePath, ios::in);

char myString[100] = {'0'};

 

while( fileReadOnly.getline(myString , 1000) ) //第二个参数是缓冲区大小

    cout<<myString;

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值