c++中使用fstream读写文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/abcxingjun/article/details/50990848

c++中封装的类库ofsream,ifstream用于文件的读写操作;
(1)ofstream–用于从流中写入文件;

    //创建并写入文件,以写文件方式打开文件
    ofstream TempOut("Test_327.txt");
    int niNum = 100;
    char name[] = "abcd";
    TempOut<< "this is a number: "<< niNum<<"\n";
    TempOut<< "this is a string: "<< name<<"\n";
    TempOut.close();

(2)ifstream用于从文件中读入程序中

//读取文件中的数据
    ifstream TempIn("Test_327.txt");
    /*char buf1[100] = {0};
    char buf[100] = {0};
    TempIn.getline(buf1,sizeof(buf1));
    TempIn.getline(buf,sizeof(buf));
    printf("%s\n",buf1);
    printf("%s\n",buf);*/
    if (TempIn.is_open())
    {
        string str;
        string str1;
        getline(TempIn,str);
        getline(TempIn,str1);
        printf("%s\n",str.c_str());
        printf("%s\n",str1.c_str());
        //cout<<str<<endl;
        //cout<<str1<<endl;
    }
    else
    {
        cout<<"打开文件失败"<<endl;
    }
    TempIn.close();

(3)说说getline()函数;
fstreasm中的getline与std::getline()中的函数是不一样的,但实现效果一样,
printf(“%s\n”,str.c_str());只能输出c字符串,string类型的变量输出时乱码,要加c_str()转换
(虽然很简单,在此记下,嘿嘿)

猜你喜欢

转载自blog.csdn.net/abcxingjun/article/details/50990848