C++文件操作示例

C++ 标准库提供了 3 个类用于实现文件操作,它们统称为文件流类,这 3 个类分别为:

ifstream:专用于从文件读取数据

ofstream:专用于向文件写入数据

fstream:可读可写

这三个文件流类都位于 fstream 头文件中;

fstream 类拥有 istream、ostream 类的全部成员方法。

示例1;读文件,

cpp 复制代码
#include <fstream>  
#include <iostream>  

using namespace std;  

void main()  
{  
	int datalen=0; 
    double num[100];
 
    //打开文件流
    ifstream file("test2.txt");
    
    //判断文件指针是否为空
    while(!file.eof() ) 
        //若不为空,则循环读取存入数组,这里的读取以空格、Tab、回车结束,以单词为单位
        file>>num[datalen++];
 
    //输出数组元素
    for(int i=0;i<datalen;i++)
    {
        cout<<num[i]<<" ";
    }
	cout<<"\n";
 
    //关闭文件流
    file.close();   
}  

示例2;写文件,

cpp 复制代码
#include <iostream>
#include <fstream>
#include<iomanip>

using namespace std;

int main() {
	
	int month = 10 , day = 1;	
	ofstream outFile;	//定义ofstream对象outFile
	
	outFile.open("me.txt");	//打开文件	
	if(!outFile) return -1;

	outFile << "国庆节:" << month << "月" << day << "日" << endl; //写入操作 	
	outFile<<setw(20)<<"姓名:"<<"张三"<<endl;
	outFile<<setw(20)<<"家庭地址:"<<"华盛顿"<<endl;
	outFile.close();	//关闭文件
	
	return 0;
}

其中,

setw用来控制输出字符串的长度,例如,

cout<<setw(10)<<"hello"<<endl;

C++会在"hello"前面加入5个空格,使"hello"的长度变为10;

使用setw需要 #include<iomanip>;

相关推荐
小七在进步7 小时前
string的使用(1)
c++·visual studio
SomeOtherTime7 小时前
Rust所有权(AI回答)
开发语言·后端·rust
Easyhood7 小时前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
白杨尚青8 小时前
C++进阶篇(六):map 和 set 的模拟实现——用红黑树封装 mymap/myset(迭代器 + operator[])
开发语言·c++·迭代器·stl·set·map·红黑树
kloc10 小时前
聊天室项目入口网关子服务的实现
linux·c++
饮水桶_T11 小时前
JAVA IO流笔记
开发语言·数据结构·算法
csdn_aspnet14 小时前
C++ 3个有序点的方向(Orientation of 3 ordered points)
c++·算法
Felven14 小时前
C. Brr Brrr Patapim
c语言·开发语言
小七在进步15 小时前
string的使用(2)
c++
路溪非溪15 小时前
python标准库使用总结
开发语言·python