如何简便的将一个文件中的内容拷到一个字符数组中?
如果将文件输入到输出流用rdbuf()就可,但是如何输入到数组中呢??
偶的傻方法:(在integer类中,ch是integer类的private成员,字符数组,初始时用memset全置为0了)
friend istream& operator>> (istream& is,integer& right)
{
//return is>>right.ch;
const sz=100;//不好!
char* pch=new char[sz];
while (is.getline(pch,sz))
{
if (*right.ch!=0)
{
strcat(right.ch,pch);
right.ch[strlen(right.ch)]='\n';
//为了保留回车用的SB方法!自己都不好意思
}
else
{
strcpy(right.ch,pch);
right.ch[strlen(right.ch)]='\n';
}
}
return is;
}
如果直接用is>>right.ch;一到空格就不读了!
请各位高手献计献策,提出简便的方法,将一个文件中的内容拷到一个字符数组中可是很常用的哟!
问题点数:0、回复次数:4Top
1 楼flyinger(风往北吹)回复于 2003-03-01 23:18:05 得分 0
#include<iostream>
#include<fstream>
#include<iterator>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
int main()
{
/* istream_iterator<string> is( cin);
istream_iterator<string> eof;
vector<string> text;
copy(is,eof,back_inserter(text));
sort(text.begin(),text.end() );
ostream_iterator<string> os(cout," ");
copy(text.begin(),text.end(),os);
*/
ifstream in_file("F:\\FlySProgrammer\\VC6\\vector\\ght.txt");
ifstream in_file2("F:\\FlySProgrammer\\VC6\\vector\\ght0.txt");
ofstream out_file("F:\\FlySProgrammer\\VC6\\vector\\ght1.txt");
if(!in_file||!out_file)
{
cerr<<"!!unable to open the necessary files .\n";
return -1;
}
istream_iterator< string > is(in_file);
istream_iterator< string > fly(in_file2);
istream_iterator< string > eof;
istream_iterator< string > f;
vector<string> text;
copy(is,eof,back_inserter(text));
copy(fly,f, back_inserter(text));
sort(text.begin(),text.end());
ostream_iterator< string > os(out_file," ");
copy(text.begin(),text.end(),os);
}
到是可以参考!呵呵!Top
2 楼flyinger(风往北吹)回复于 2003-03-01 23:19:32 得分 0
我是把两个文件多到那个Text中啊!最后保存到了哪个ght1.txt中了!Top
3 楼trailblazer(开路先锋)回复于 2003-03-03 12:00:04 得分 0
能不能少用一些STL内容,用更基础的实现方法??Top
4 楼OstrichFly(飞翔的鸵鸟)回复于 2003-03-03 12:05:00 得分 0
windows可以直接用内存映射文件,把整个文件映射到内存中就行了,而且性能较好Top




