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

相关推荐
一只小透明啊啊啊啊6 分钟前
Socket、AIDL、SOME/IP
c++·mcu
伞伞悦读1 小时前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json
CCCCCCCCharlie1 小时前
Linux进程控制四大核心操作
linux·开发语言
Tim_101 小时前
【LeetCode】338、比特位计数
c++·算法·leetcode
Brilliantwxx1 小时前
【STM32】 SPI Flash 驱动开发实战:阻塞模式驱动 W25Q64(含工程代码)
开发语言·stm32·单片机·嵌入式硬件
wuyk5551 小时前
【Socket 进阶之路】第 9 章 Linux 网络服务量产稳定性优化|心跳保活、TIME_WAIT、SO_LINGER、内存池、断线重连、完整异常防护框架
linux·服务器·开发语言·网络·物联网
邪修king2 小时前
Re:Linux 系统篇(三十四):进程间通信开篇Chapter1 —— 匿名管道 pipe 深度拆解与代码实战
android·linux·运维·开发语言
程序员AlbertTu2 小时前
# Mantissa 使用教程 — Python 版与 C++ 版
c++·python·数值运算