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;
}



原文地址:https://www.cnblogs.com/OFSHK/p/11246827.html