【C++】windows下使用c++将数据输出到文件 —— 9
发布日期:2021-05-15 02:52:05 浏览次数:18 分类:精选文章

本文共 1553 字,大约阅读时间需要 5 分钟。

一、函数功能

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

二、代码

#include 
#include
#include
#include
#include
#include
using namespace std;#define MAX_PATH 1000int 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. 文件内容:

    在这里插入图片描述

上一篇:【SQL】修改数据库编码格式以支持中文——1
下一篇:【C++】pinv()函数原型以及matlab中的pinv() —— 8

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2025年04月07日 22时33分42秒