zoukankan      html  css  js  c++  java
  • 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;
    }



  • 相关阅读:
    IDEA
    SpringCloud
    Docker
    Docker
    JDK排序
    选择排序
    冒泡排序
    计算一个整数数组的平均数
    (if语句)中国的个税计算方法
    读入一个表示年份的整数,判断这一年是否是闰年
  • 原文地址:https://www.cnblogs.com/OFSHK/p/11246827.html
Copyright © 2011-2022 走看看