区别一:本质不一样
1、ofstream是从内存到硬盘;
2、ifstream是从硬盘到内存
区别二:实际应用不同
1、 ifstream默认以输入方式打开文件
2、ofstream默认以输出方式打开文件
扩展资料
1、C++对文件的输入输出操作需要用ifstream、ofstream和fstream类。
2、ifstream类支持文件的输入,ofstream类支持文件的输出操作,fstream类支持文件的输入输出操作,它们的定义在头文件<fstream>中。
3、C++将字符串也理解为一种输入输出设备,因此,也可以向终端设备和文件那样将数据输入输出到字符串中。
c++中输出和输入导屏幕和键盘的类别声明包含再标题文件<iostrream.h>中,而磁盘类文件的 I/O则声明再包含标题文件<fstream.h>内。
输入和输出格式:
输出到磁盘 ofsteam 识别字(“文件名”)
从磁盘读文件 ifsteam 识别字(”文件名“)
例如:
ofstream outfile(”data.txt”)//写入到磁盘的data.txt中
c++ ifstream函数的使用
#include <iostream>
#include <fstream>
#include <string>
using namespace std
//输出空行
void OutPutAnEmptyLine()
{
cout<<”\n”
}
//读取方式: 逐词读取, 词之间用空格区分
//read data from the file, Word By Word
//when used in this manner, we’ll get space-delimited bits of text from the file
//but all of the whitespace that separated words (including newlines) was lost.
void ReadDataFromFileWBW()
{
ifstream fin(”data.txt”)
string s
while( fin >>s )
{
cout <<”Read from file: ” <<s <<endl
}
}
//读取方式: 逐行读取, 将行读入字符数组, 行之间用回车换行区分
//If we were interested in preserving whitespace,
//we could read the file in Line-By-Line using the I/O getline() function.
void ReadDataFromFileLBLIntoCharArray()
{
ifstream fin(”data.txt”)
const int LINE_LENGTH = 100
char str[LINE_LENGTH]
while( fin.getline(str,LINE_LENGTH) )
{
cout <<”Read from file: ” <<str <<endl
}
}
//读取方式: 逐行读取, 将行读入字符串, 行之间用回车换行区分
//If you want to avoid reading into character arrays,

//you can use the C++ string getline() function to read lines into strings
void ReadDataFromFileLBLIntoString()
{
ifstream fin(”data.txt”)
string s
while( getline(fin,s) )
{
cout <<”Read from file: ” <<s <<endl
}
}
//带错误检测的读取方式
//Simply evaluating an I/O object in a boolean context will return false
//if any errors have occurred
void ReadDataWithErrChecking()
{
string filename = ”dataFUNNY.txt”
ifstream fin( filename.c_str())
if( !fin )
{
cout <<”Error opening ” <<filename <<” for input” <<endl
exit(-1)
}
}
int main()
{
ReadDataFromFileWBW()//逐词读入字符串
OutPutAnEmptyLine()//输出空行
ReadDataFromFileLBLIntoCharArray()//逐词读入字符数组
OutPutAnEmptyLine()//输出空行
ReadDataFromFileLBLIntoString()//逐词读入字符串
OutPutAnEmptyLine()//输出空行
ReadDataWithErrChecking()//带检测的读取
return 0
}
string 是stl里的模板,是为了方便字符串操作,当然不能传,可以用char数组,
#include<iostream>
#include<fstream>
using namespace std
chara[50]
{
while(true)
{
cin>> a
ifstream fin(a)
longtemp
fin>>temp
fin.close()
}
}
手机,没编译,有错请讲
以上就是关于C++中,ifstream和ofstream定义文件流的区别全部的内容,如果了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!