C++ 文件流fstream对象操作文件(文本文件和二进制文件)

 

1. 文本文件的操作 直接 用文件流对象 的 << 和 >> 来操作,和 cout<>x,一样:

    ofile<<"just do it" ----->   就是把 字符串 写入到 ofile对象关联的文件名中

    ifile>>s ------> 就是从ifile关联的文件中读取一个单词(不一定是一个单词,就是遇到空格就结束) 赋给s

 

2. 文件流对象还有2个操作函数read(),write(),这2个函数的第一个参数只能是 C_String 即 char* s,第二个参数是读写的字节数

     read()和write()要指定读写字节数,因此 是用来操作 二进制文件的.

 

#include 
#include 
#include 
using namespace std;
void main()
{
	string s,filename = "c:/cpptest.dat";	
    fstream file;	
	 file.open(filename.c_str(),ios::binary|ios::out);

	char* istr = "just do it"; //14
	for(int i=0;i<10;i++)
	{
		file.write(istr,strlen(istr));
	}

	    file.close();
		file.clear();

		char* ch=NULL;
		file.open(filename.c_str(),ios::binary|ios::in);
		for(i=0;i<10;i++)
		{
			 file.read(ch,strlen(istr));
		     if(file.tellg()>0) cout<<*ch<


<> P627--635 根本就没有提到这2个函数

<> P251  也压根就没有提这2个函数

被奉为圣经的书提都不提.

 

http://www.cplusplus.com/reference/iostream/ostream/write/ 

 下面的代码中 用long size  作为 tellg()的返回值是不对的.

 <>  P634-635 有讲:

应该是 std::ios::pos_type size  而不是 long size

这样写: std::streampos size 也可以.

 

// Copy a file
#include 
using namespace std;

int main () {
	
	char * buffer;
	long size;
	
	ifstream infile ("test.txt",ifstream::binary);
	ofstream outfile ("new.txt",ofstream::binary);
	
	// get size of file
	infile.seekg(0,ifstream::end);
	size=infile.tellg();
	infile.seekg(0);
	
	// allocate memory for file content
	buffer = new char [size];
	
	// read content of infile
	infile.read (buffer,size);
	
	// write to outfile
	outfile.write (buffer,size);
	
	// release dynamically-allocated memory
	delete[] buffer;
	
	outfile.close();
	infile.close();
	return 0;
}


 http://www.cplusplus.com/reference/iostream/istream/read/

同理 下面的 length 也必须定义为: std::ios::pos_type length 而不是 int length

 或者 std::streampos length

// read a file into memory
#include 
#include 
using namespace std;

int main () {
  int length;
  char * buffer;

  ifstream is;
  is.open ("test.txt", ios::binary );

  // get length of file:
  is.seekg (0, ios::end);
  length = is.tellg();
  is.seekg (0, ios::beg);

  // allocate memory:
  buffer = new char [length];

  // read data as a block:
  is.read (buffer,length);
  is.close();

  cout.write (buffer,length);

  delete[] buffer;
  return 0;
}


 

你可能感兴趣的:(C/C++)