10.C++ 文件流 Mac

文件的输出流的应用

#include <iostream>
#include <fstream>
int main(int argc, const char * argv[])
{
    //文件的读写
    char str[100];
    std::ofstream myFileOut("/Users/x/Desktop/test.txt",std::ios::out);//创建输出流对象
    if (myFileOut.fail()) {
        std::cout<<"文件不存在"<<std::endl;
        return 0;
    }
    else
    {
        std::cout<<"成功打开文件"<<std::endl;
    }
    
    for (int i=0; i<4; i++) {
        std::cin>>str;
        myFileOut<<str<<std::endl; //通过对象myFileOut 进行写出操作 写入文件
    }
    myFileOut.close();//关闭文件
    return 0;
}


文件输入流的应用

#include <iostream>
#include <fstream>
int main(int argc, const char * argv[])
{
    char str[100];
    std::ifstream myFileIn("/Users/x/Desktop/test.txt",std::ios::in);//创建输入流对象
    if (myFileIn.fail()) {//判断文件是否存在,如果存在则调用open函数打开
        std::cout<<"文件不存在"<<std::endl;
        return 0;
    }
    else
    {
        std::cout<<"成功打开文件"<<std::endl;
    }
    
    for (int i=0; i<4; i++) {
        myFileIn>>str;
        std::cout<<str<<std::endl;
    }
    myFileIn.close();//关闭问价
}


#include <iostream>
#include <fstream>
int main(int argc, const char * argv[])
{
    char str;
    std::ifstream fileRead("/users/x/desktop/read.txt",std::ios::in);//打开文件用于读文件
    while ( !fileRead.eof()) {//判断是否读完文件
        fileRead.read(&str, 1);
        std::cout<<str;
    }
    fileRead.close();
}


随机文件访问应用

#include <iostream>
#include <fstream>
#include <string>
int main(int argc, const char * argv[])
{
    char i,str[50]={"readwriteclose"};
    std::fstream file("/users/x/desktop/read.txt",std::ios::in|std::ios::out|std::ios::binary);//打开当前目录文件
    if ( !file) {
        std::cerr<<"文件打开失败"<<std::endl;
        return 0;
    }
    
    file.write(str, strlen(str));//将str写入文件
    file.close();
    file.open("/users/x/desktop/read.txt",std::ios::in|std::ios::binary);
    file.seekg(3);//将文件指针移到第3个字节后
    file.read(&i, 1);
    std::cout<<"第四个数是:"<<(int)i<<std::endl;
    
    i='!';
    file.seekg(4);//将文件指针移到第4个字节后
    file.put(i);//将i值写入第5个字节
     std::cout<<"第5个数是:"<<i<<std::endl;
    file.close();
    
}



  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值