C++将数据写入到txt文件中,并在文件名中加上时间戳

1.获取时间要用到的头文件

#include<time.h>
#include<string>

2.使用写入文件需要使用的头文件

#include<fstream>

3.获取当前系统时间到string变量filename(随便起的)中,因为char类型的数组变量无法使用 + 来组合你想要的名字

//代码前要声明名称空间std
time_t currentTime=time(NULL);//注意NULL大小写
char chCurrentTime[256];
strftime(chCurrentTime,sizeof(chCurrentTime),%Y%m%d %H%M%S,localtime(&chCurrentTime));
string stCurrentTime=chCurrentTime;
string filename="data"+stCurrentTime+".txt";

4.要写入文件需要创建一个ofstream对象

ofstream fout;

5.然后需要将这个对象与文件关联起来,使用open()函数,文件即之前我们将时间戳整合得到的filename
使用open函数打开文件时,如果没有该文件则默认创建一个此名称的文件,如果已有该文件则默认覆盖之前内容,具体可以查阅相关资料

fout.open(filename.c_str());//文件名后面一定要加这个.c_str()    该函数返回一个指针常量,因为貌似open()函数没法直接加string的变量,返回的字符串与string内容相同

6.之后就是往该文件里面写入内容,使用方法与cout相同

fout<<"test"<<endl;

7.最后将文件关闭即可

fout<<flush;//确保文件在无操作时关闭   可以省略
fout.close();

最后写了一个简单的小例子

#include <fstream>
#include<iostream>
#include<time.h>
#include<string>
int main()
{
	using namespace std;

    time_t currentTime=time(NULL);
	char chCurrentTime[256];
	strftime(chCurrentTime,sizeof(chCurrentTime),"%Y%m%d %H%M%S",localtime(&currentTime));
    string stCurrentTime=chCurrentTime;
    string filename="data"+stCurrentTime+".txt";
    
	ofstream fout;
	fout.open(filename.c_str());
	int v_set,v_act,a_set,a_act;
	int i=0;
	while(i<5)
	{
		cin>>v_set>>v_act>>a_set>>a_act;
    	fout<<v_set<<", "<<v_act<<", "<<a_set<<", "<<a_act<<", "<<endl;
    	i++;
    }
	fout<<flush;
	fout.close();
}

运行之后会在程序目录下得到一个txt文件,效果如下
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值