c语言的文件流操作(小总结)

今天有个小失误,文件读取出错,下面总结一下,直接文件复制,呵呵
方式一:直接复制
void main () 
{ 
	fstream examplefile("example.txt",ios::in); 
	ofstream SaveFile("cpp-home1.txt"); 
	if (! examplefile.is_open()) 
	{ cout << "Error opening file"; exit (1); }
	[color=red]SaveFile<<examplefile.rdbuf();[/color]
	system("pause"); 
} 

方式二:逐行复制
void main () 
{ 
	fstream examplefile("example.txt",ios::in); 
	ofstream SaveFile("cpp-home1.txt"); 
	if (! examplefile.is_open()) 
	{ cout << "Error opening file"; exit (1); }
	examplefile.seekg(0,ios::end); 
	streampos  pos=examplefile.tellp();
	examplefile.seekg(0);
	char *buffer; 
	buffer=new char [pos]; //开辟了足够的空间 呵呵 整个文件大小
	while (examplefile.getline(buffer,pos))
	{
		SaveFile.seekp(0,ios::end); //移到输出文件末
		SaveFile<<buffer<<endl;
	}
	delete [] buffer;
	system("pause"); 
} 

方式三:逐字符复制(不过控制符、制表符等不存在)
void main () 
{ 
	char temp;
	fstream examplefile("example.txt",ios::in); 
	ofstream SaveFile("cpp-home1.txt"); 
	if (! examplefile.is_open()) 
	{ cout << "Error opening file"; exit (1); }
	while (!examplefile.eof())
	{
		examplefile>>temp;
		SaveFile<<temp;
		cout<<temp<<endl;
	}
	system("pause"); 
} 

修改一下,使用get和put 可以显示控制符和制表符等
void main () 
{ 
	char temp;
	fstream examplefile("example.txt",ios::in); 
	ofstream SaveFile("cpp-home1.txt"); 
	if (! examplefile.is_open()) 
	{ cout << "Error opening file"; exit (1); }
	while (!examplefile.eof())
	{
		examplefile.get(temp);
		SaveFile.put(temp);
		cout<<temp<<endl;
	}
	system("pause"); 
} 

你可能感兴趣的:(ios,C++,c,C#)