【C++】windows下使用c++将数据输出到文件 —— 9

一、函数功能

将得到的数据输出到指定路径文件内

二、代码

#include <iostream>
#include <windows.h>
#include <process.h> 
#include <fstream>
#include <ctime>
#include <direct.h>

using namespace std;

#define MAX_PATH 1000

int main() 
{
	double a = 15.5;
	double b = 22.5;
	int c = 0;

	char buffer[MAX_PATH];
	_getcwd(buffer, MAX_PATH);	//当前路径为 D:\vs_test\test2\test2
	cout << "当前路径为: " << buffer << endl << endl;

	//1.相关数据输出文件的建立
	//string pathname = "D:\\vs_test\\test2\\FileData\\";	//绝对路径
	string pathname = "..\\FileData\\";	//相对路径
	time_t t = time(0);
	char ch[64];
	strftime(ch, sizeof(ch), "%Y-%m-%d %H-%M-%S", localtime(&t)); //年-月-日 时-分-秒
	std::string paitent_info = "test_";
	ofstream test_value(pathname + paitent_info + "joint_" + ch + ".txt", ios::app | ios::out);

	test_value << " a(N.m)  " << "    b(N.m)  " << endl;

	//2.循环,打印数据
	while (c < 10) {
		a += 1;
		b += 2;
		c++;
		test_value << " " << a << "     " << b << std::endl;
		printf("a = %f\n", a);
	}	

	//3.文件关闭
	test_value.close();
	return 0;
}

三、代码讲解

  1. _getcwd(buffer, MAX_PATH);
    1)函数功能:获取文件的当前路径。
    2)在Windows VS2017环境下,头文件是#include <direct.h>

  2. string pathname = "D:\\vs_test\\test2\\FileData\\"; 这是设置绝对路径,将我们要输出的数据保存在FileData这个文件夹下

  3. string pathname = "..\\FileData\\"; 这是设置相对路径。

  4. strftime(ch, sizeof(ch), "%Y-%m-%d %H-%M-%S", localtime(&t));得到当前时间:年-月-日 时-分-秒

  5. ofstream test_value(pathname + paitent_info + "joint_" + ch + ".txt", ios::app | ios::out);
    生成文件,文件的名称是:“test_”+“joint_”+“时间”+“.txt”,
    即:test_joint_2020-11-03 09-42-29.txt

  6. 在循环里面,将数据a、b储存在文件test_joint_2020-11-03 09-42-29.txt

  7. test_value.close();关闭文件

四、打印结果

  1. 运行之后,结果为:
    在这里插入图片描述

  2. 文件路径:
    在这里插入图片描述

  3. 文件内容:
    在这里插入图片描述

  • 7
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wolves_liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值