浏览器标题切换
浏览器标题切换end

C/C++ - 文件操作(一)

#include<iostream>
#include<string>
#include<cmath>
#include<cstdio> // FILE操作头文件。没有的话,CLION不会报错,直接显示自己设置的不能打开的语句,codeblocks会报错。
using namespace std;
const double PI=acos(-1.0);


int main()
{
FILE *fp=fopen("/Users/cih/Desktop/A.txt","r");
if(fp!=NULL)
{
int x;
fscanf(fp,"%d",&x);
cout<<x<<endl;
fclose(fp);
}
else
cout<<"Can't open it!"<<endl;
return 0;
}


// 用>和<做重定向



复制代码
#include<iostream>
#include<string.h>
#include<fstream> // 需要包含该头文件
using namespace std;

//    ofstream 写
//    ifstream 读
//    fstream 读写

int main()
{
    写文件
    ofstream ofs; // 创建流对象
    ofs.open("路径 test.txt",打开方式);
    打开方式:ios::in/out 读/写文件
    ofs<<"写入的数据"
       ofs.close();// 关闭文件


    读文件
    ifstream ifs;
    ifs.open("test.txt",ios::in);
    if(!ifs.is_open()) // 判断文件是否打开成功
        cout<<"Fail"<<endl;
    ifs.close();
    读数据方式1:
    char buf[110]= {0};
    while(ifs>>buf) // 全部读完跳出while
        cout<<buf<<endl;
    ifs.close();
    读数据方式2:
    char buf[110]= {0};
    while(ifs.getline(buf,110/sizeof(buf))) //char * ,最多读多少字节数
        cout<<buf<<endl;
    读数据方式3:
    string buf;
    while(getline(ifs,buf))
        cout<<buf<<endl;
    ifs.close();
    
    return 0;
}
复制代码

 




posted @   抓水母的派大星  阅读(195)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示