使用ftream进行多次读写

时间:2016-11-07 15:54:46

标签: c++ file stream fstream

我正在尝试使用fstream执行读写操作,我不想多次打开和关闭文件。可能吗?如果是的话怎么做。 这是我尝试过但它不起作用..

   /*
 Write a menu driven C++ program to create a single line text file and then implement the following:
 a) Convert every lower case letter to upper case and upper case letter to lower case.
  b) Display the content of the file.   

*/
#include<iostream>
#include<fstream>
#include<cstring>
const int size=100;
char casecnvrt(char c)//case convertion operations
{
        if(c>='A'&&c<='Z')c+=32;
        else if(c>='a'&&c<='z')c-=32;

}
using namespace std;
int main()
{
    char s1[size],s2[size],s3[size],c;
    int op,i=0;
    fstream file1;
    ifstream file2;

    while(1){
    file1.open("p1.txt",ios::trunc|ios::out|ios::in);//i dont want to append
    if(!file1)
    {
        cout<<"Unable create file1\n";//return 0;
    }
    cout<<"\n1.enter Text\n2.convert letters\n3.display\n4.Exit\nEnter Your choice :";
    cin>>op;
    switch(op)
    {
        case 1 :cout<<"Enter a line\n";
                cin.ignore();
                cin.getline(s1,size);
                file1<<s1;
                cout<<"\nFile Has Been Written,...";break;
        case 2 : file1.seekg(0);
                    while(file1)
                    {
                        file1.get(c);
                        s2[i++]=casecnvrt(c);
                    }
                    file1.seekp(0);
                cout<<s2;
                 file1<<s2;
                 cout<<"\nCase Convertion Done...";break;
        case 3 : file1.seekg(0);
                 file1>>s3;
                 cout<<s3;
                 break;
        case 4 : file1.close();return 0;
        default: cout<<"\nInavalid choice\n";

    }
    file1.close();
}
    return 0;
}

提前感谢..

0 个答案:

没有答案