文件的读写

来源:互联网 发布:php面向对象面向过程 编辑:程序博客网 时间:2024/05/18 19:35

在getline那边挣扎好久,终于算是编译通过,写出来了。这算是我打响学习的第一炮,接下来继续努力。

int main()
{
    string buff ;
    char filename[30];
    ofstream infile;
    cout << "please input filename" << endl;
    cin >> filename;
    cout << endl;
    infile.open(filename,ios::out|ios::app) ;
    if(!infile)
    {
        cerr<<"open failed" << filename <<endl;
        exit(0);
    }
    infile << "i" <<" ";
    infile << "love" << " "    ;
    infile << " you " << " ";
    cout << "input number:" << endl;
    cin >> buff;
    infile << buff << endl;
    infile.close();

    ifstream onfile;
    onfile.open(filename);
    if(!onfile)
    {
        cerr<< "open failed" << filename << endl;
        exit(0);
    }
    onfile.seekg(0,ios::end);
    double m_nLength = onfile.tellg();
    onfile.seekg(0);
    cout << "The number is:" << endl;
    char *str = (char*)malloc((m_nLength)*sizeof(char));
    while(onfile.getline(str,m_nLength,'\n'))
     //while(getline (onfile,str))
        cout<<str;
    onfile.close();
    return 0;
}

原创粉丝点击