C++语言程序设计(清华大学郑莉)11.pptVIP

  • 12
  • 0
  • 约1.21万字
  • 约 52页
  • 2016-10-17 发布于湖北
  • 举报
C语言程序设计(清华大学郑莉)11

* * * * 打开文件的方法(一)举例 #includefstream using namespace std; void fn() { ofstream myf(mydata); if(myf.fail()) { cerrerror\n; return; } myf.....; } 例:ifstream myinf(“abc.dat”,ios::nocreate); 例:fstream myinout(“abc.dat”,ios::in|ios::out); * 打开文件的方法(二) 首先建立一个对象,在需要时再由open()函数将流对象和一个具体的文件相连 ifstream::open(char*,int=ios::in,int=filebuf::openprot) ofstream::open(char*,int=ios::out,int=filebuf::openprot) fstream::open(char*,int,int=filebuf::openprot) e.g. ofstream output; output.open(“output.dat”) * 文件关闭 void ifstream::close() void ofstream::close() void fstream::close() e.g. output.close(); * 文本文件的使用 对文本文件读写方法与标准输入/输出流cin,cout的使用方法相同。 例:将源文件拷贝到目的文件 * 文本文件使用例1 #includeiostream.h #includefstream.h #includestdlib.h void main() { char filename1[256],filename2[256]; cout“input source name:”; cinfilename1; cout“input target name:”; cinfilename2; ifstream infile(filename1); ofstream outfile(filename2); * 文本文件使用例1(续) if(!infile) { cout“can’t open”filename1“\n”; exit(1); } //判断文件1是否打开成功 if(!outfile) { cout“can’t open”filename2“\n”; exit(1); } //判断文件2是否打开成功 char ch; while(infile.get(ch)) outfile.put(ch); infile.close(); outfile.close(); } * 文本文件使用例2 设文本文件data.txt中有若干实数,每个实数之间用空格或换行符隔开,求出文件中的这些实数的平均值。 #includeiostream.h #includefstream.h #includestdlib.h void main() { float sum=0,temp; int count=0; * 文本文件使用例2(续) ifstream infile(“data.txt”); if(!infile) { cout“can’t open data.txt”“\n”; exit(1);    } while(infiletemp) { sum+=temp; count++; } cout“result:”sum/count“”\n; infile.close(); } * 二进制文件使用 对二进制文件的读写操作 istream istream::read(char*,int); 将由第二个参数所指定的字节数读到由第一个参数所指定的字符型指针所指向的存储单元中。 ostream ostream::write(char*,int); 第二个参数指定的写入的字节数,第一个参数指定要写到文件中的字节串的起始地址。 * 文件读二进制记录 #include iostream #include fstream #include cstring using namespace

文档评论(0)

1亿VIP精品文档

相关文档