C++语言基础 例程 文本文件的读写
来源:互联网 发布:做网站java还是php 编辑:程序博客网 时间:2024/06/04 00:47
贺老师的教学链接 本课讲解
示例:将数据写入ASCII文件
#include <iostream>#include <fstream>#include <cstdlib>using namespace std;int main( ){ int a[10]; ofstream outfile("f1.dat",ios::out);//定义文件流对象,打开磁盘文件"f1.dat" if(!outfile) //如果打开失败,outfile返回0值 { cerr<<"open error!"<<endl; exit(1); } cout<<"enter 10 integer numbers:"<<endl; for(int i=0; i<10; i++) //向磁盘文件"f1.dat"输出数据 { cin>>a[i]; outfile<<a[i]<<" "; } cout<<"The numbers have been writen to file. "<<endl; outfile.close(); //关闭磁盘文件"f1.dat" return 0;}
示例:从ASCII文件读入数据
#include <iostream>#include <fstream>#include <cstdlib>using namespace std;int main( ){ int a[10],max,i,order; ifstream infile("f1.dat",ios::in); //定义输入文件流对象,以输入方式打开磁盘文件f1.dat if(!infile) { cerr<<"open error!"<<endl; exit(1); } for(i=0; i<10; i++) { infile>>a[i]; //从磁盘文件读入10个整数,顺序存放在a数组中 cout<<a[i]<<" "; } //在显示器上顺序显示10个数 cout<<endl; max=a[0]; order=0; for(i=1; i<10; i++) if(a[i]>max) { max=a[i]; //将当前最大值放在max中 order=i; //将当前最大值的元素序号放在order中 } cout<<"max="<<max<<endl<<"order="<<order<<endl; infile.close(); return 0;}
示例:读写ASCII文件
#include<iostream>#include <fstream>#include <cstdlib>using namespace std;void save_to_file( );void get_from_file();int main( ){ save_to_file( ); get_from_file( ); return 0;}void save_to_file( ){ ofstream outfile("f2.dat"); if(!outfile) { cerr<<"open f2.dat error!"<<endl; exit(1); } char c[80]; cin.getline(c,80); for(int i=0; c[i]!=0; i++) if(c[i]>='a' && c[i]<='z') outfile.put(c[i]); outfile.close(); }void get_from_file(){ char ch; ifstream infile("f2.dat",ios::in); if(!infile) { cerr<<"open f2.dat error!"<<endl; exit(1); } ofstream outfile("f3.dat"); if(!outfile) { cerr<<"open f3.dat error!"<<endl; exit(1); } while(infile.get(ch)) outfile.put(ch-32); infile.close( ); outfile.close(); }
示例:在显示器上输出文件
#include <iostream>#include <fstream>#include <cstdlib>using namespace std;void display_file(char *filename);int main( ){ display_file("f3.dat"); return 0;}void display_file(char *filename){ ifstream infile(filename,ios::in); if(!infile) { cerr<<"open error!"<<endl; exit(1); } char ch; while(infile.get(ch)) cout.put(ch); cout<<endl; infile.close();}
0 0
- C++语言基础 例程 文本文件的读写
- C++语言基础 例程 文件的随机读写
- C语言基础及例程
- C#:读写简单的文本文件
- c#winform文本文件的读写
- C++语言基础 例程 二进制文件及其顺序读写
- C语言及程序设计进阶例程-36 文件的随机读写
- c:文本文件的读写(simple版)
- C语言及程序设计进阶例程-37 二进制文件及其读写
- 读写文本文件(C#)
- Objective-c 读写文本文件
- c/c++读写文本文件
- Objective-c 读写文本文件
- 利用标准C语言库函数进行文本文件读写
- C++语言基础 例程 多态性的概念
- C语言及程序设计初步例程-42 将数据输出到文本文件
- C语言及程序设计初步例程-43 从文本文件中读入数据
- 第3周 C语言及程序设计初步例程-42 将数据输出到文本文件
- poj1595 prime cuts(快速筛选)
- C++语言基础 例程 C++的输入输出与流对象
- C++语言基础 例程 标准输出流
- Php link to MySQL
- C++语言基础 例程 标准输入流
- C++语言基础 例程 文本文件的读写
- C++语言基础 例程 二进制文件及其顺序读写
- C++语言基础 例程 案例:bmp文件格式剖析
- C++语言基础 例程 文件的随机读写
- C++语言基础 例程 字符串流
- C++语言基础 例程 二进制文件应用案例
- Convert pdf to image
- Own (and Refactor) the Build
- Android 进行单元测试难在哪-part1