怎么用fstream读取文件里存的内容

来源:百度知道 编辑:UC知道 时间:2024/06/17 03:11:36
就是我有txt文档里面存点东西。然后在C++里面读取文件里的内容。就是我运行后会显示出来文本里面的内容。要可以逐行读取的。

C++中的文件流有三种:
  ifstream - 由istream派生而来,提供读文件的功能
  ofstream - 由ostream派生而来,提供写文件的功能
  fstream - 由iostream派生而来,提供读写同一个文件的功能
  文件流在打开文件的时候需要说明打开模式:in - 打开文件做读操作;out - 打开文件做写操作;app - 每次写之前找到文件尾;ate - 打开文件后立即将文件定位在文件尾;trunc - 打开文件时清空已存在的文件流。
  其中out、trunc 和 app模式只能够与ifstream或fstream对象关联,所有的文件流对象都可以 ate 和 binary。

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
char str[255];
ifstream in("d:\\a.txt");//文件名这地方输入你的文件所在路径及文件名对应的字符串
if(!in)
{
cout<<"Cannot open file.\n";
return 1;
}

while(in)
{
in.getline(str,255);//读取一行
if(in) cout<<str<<endl;
}
in.close();
return 0;
}

这里假定读取d盘根目录下a.txt文件

FILE *stream;
char line[255];

int j=0;
if( (stream = fopen( "aa.txt ", "r &qu