在使用C++编写的程序中,如何从一个文件把数据读入程序?

如题所述

文件流类:

(1) ifstream ifile:只输入用,它是从istream 类派生的。

(2) ofstream ofile:只输出用,它是从ostream 类派生的。

(3) fstream iofile:既输入又输出用,它是从iostream 类派生的。

//应用举例

#include"iostream.h"

#include "fstream.h"

#include "stdlib.h"

void main()

{char s[100];

ofstream outf;

outf.open("dialogue.dat");

if(!outf)

{cout<<"can't open dialogue.dat"<<endl;

abort();

}

outf<<"How are you?\n"; //通过插入操作将若干字符串写到文件中

outf<<"I'm fine,thank you.and you?\n";

outf<<"I'm very well.\n";

outf.close();

ifstream inf("dialogue.dat");

while(!inf.eof())

{inf.getline(s,sizeof(s)); //通过getline 函数从文件中读一行

//字符串到数组

cout<<s<<endl;

}

}

温馨提示:内容为网友见解,仅供参考
第1个回答  2010-12-04
//额。。你是要C++的代码对不?? 我是用C++ STL 写的,你看看满足要求不,如果
///可以的话,咱在继续交流。。。呵呵。。。
//代码我没有加注释,你感兴趣的话,在深交。。。

#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <iterator>
#include <vector>
#include <fstream>
using namespace std;
int main()
{ string input_file_name;
string output_file_name;
cout<<"input the in_file_name: "<<endl;
cin>>input_file_name;
cout<<"input the output_file_name: "<<endl;
cin>>output_file_name;

ifstream f_in(input_file_name.c_str());
ofstream f_out(output_file_name.c_str());
if(!f_in || !f_out) {
cout<<"can't open the file!"<<endl;
exit(0);
}

istream_iterator<char> is(f_in);
istream_iterator<char> eof;
vector<char> text;
copy(is,eof,back_inserter(text));
ostream_iterator<char> os(f_out,"");
copy(text.begin(),text.end(),os);
cout<<"the copy is over ! "<<endl;
return 0;

}

http://hi.baidu.com/sx_liang/blog/item/254d98e98336065e79f05579.html
这个是我的博客,里边也许有你想要的信息。。。你看看 。祝:学业有成。。。本回答被提问者和网友采纳
相似回答