字符串文件流的实现

来源:互联网 发布:linux端口映射 命令 编辑:程序博客网 时间:2024/06/10 10:46
#include <iostream>#include <fstream>using namespace std;int main(){    /*读取文件中的150个数字,算出和并写进去 */    //先把数字写进去    //构造函数法(建立流和文件的关系有两种方法)    ifstream ifile1("/Users/riverspace/myCpp/Data1.txt",ios::in);//原始数据1    ofstream ofile1("/Users/riverspace/myCpp/Data1.txt",ios::out);    ifstream ifile2("/Users/riverspace/myCpp/Data2.txt",ios::in);//原始数据2    ofstream ofile2("/Users/riverspace/myCpp/Data2.txt",ios::out);    ofstream ofile3("/Users/riverspace/myCpp/Data3.txt",ios::out);//相加结果    ofstream ofile5("/Users/riverspace/myCpp/Data5.txt",ios::out);//相除结果    for(int i=0;i<150;i++){        ofile1<< i+1 << ' ';        if ((i+1)%10==0){    //后面再++的这里要i+1            ofile1<<endl;        }    }    for (int j=0;j<150;j++){        ofile2<< j+1<< ' ';        if((j+1)%10==0){            ofile2<<endl;        }    }    //求和与相除,结果写进去    int a[150],b[150],c[100],d[100];    for(int temp1=0;temp1<150;temp1++) {        ifile1 >> a[temp1];               //用ifile1文件流对应的数字填满数组a        ifile2 >> b[temp1];        c[temp1] = a[temp1] + b[temp1];        d[temp1] = a[temp1] / b[temp1];   //数组a和数组a的前n个元素相除,存在p1中然后出去        ofile3 << c[temp1] << ' ';        ofile5 << d[temp1] << ' ';        if ((temp1 + 1) % 10 == 0) {            ofile3 << endl;            ofile5 <<endl;        }    }    //使用结束用,要切断流和文件的关系(只有一种方法)    ifile1.close();ofile1.close();ifile2.close();ofile2.close();ofile3.close();ofile5.close();    /* 文件流的另一种方式*/    fstream file;     //声明一个对象    file.open("/Users/riverspace/myCpp/Data6.txt");//用对象成员函数打开文件    if(!file){       //测试是否真的打开了文件        cout<<"can't open data6.txt"<<endl;        exit(1);    }    //对文本文件进行处理    char ch1;    char ch2[] = "Nanjing";    char ch3[20];    char *p4;    cin.get(ch1);    cout<<ch1<<endl;    file<<ch2<<endl;cout<<"ch2='Nanjing'已输出到Data6.txt"<<endl;    cout<<ch2<<endl;    cout<<"请输入ch3,20位"<<endl;    cin.getline(ch3,20,'l');    file<<ch3<<endl;cout<<"ch3已输出到Data6.txt"<<endl;    file.close();    //关闭文本文件    p4=ch3;    cout<<"p4="<<p4<<endl;    return 0;}
原创粉丝点击