
【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)函数功能:获取文件的当前路径。 2)在Windows VS2017环境下,头文件是_getcwd(buffer, MAX_PATH);
#include <direct.h>
-
string pathname = "D:\\vs_test\\test2\\FileData\\";
这是设置绝对路径,将我们要输出的数据保存在FileData
这个文件夹下 -
string pathname = "..\\FileData\\";
这是设置相对路径。 -
strftime(ch, sizeof(ch), "%Y-%m-%d %H-%M-%S", localtime(&t));
得到当前时间:年-月-日 时-分-秒
-
生成文件,文件的名称是:“test_”+“joint_”+“时间”+“.txt”, 即:ofstream test_value(pathname + paitent_info + "joint_" + ch + ".txt", ios::app | ios::out);
test_joint_2020-11-03 09-42-29.txt
-
在循环里面,将数据a、b储存在文件
test_joint_2020-11-03 09-42-29.txt
中 -
test_value.close();
关闭文件
四、打印结果
-
运行之后,结果为:
-
文件路径:
-
文件内容:
发表评论
最新留言
网站不错 人气很旺了 加油
[***.192.178.218]2025年04月07日 22时33分42秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
javaWeb服务详解(含源代码,测试通过,注释) ——Emp的Dao层
2019-03-11
java实现人脸识别源码【含测试效果图】——Dao层(IUserDao)
2019-03-11
使用ueditor实现多图片上传案例——前台数据层(Index.jsp)
2019-03-11
解决Chrome播放视频闪屏黑屏无法播放
2019-03-11
Git简单理解与使用
2019-03-11
echarts 基本图表开发小结
2019-03-11
制作JS验证码(简易)
2019-03-11
adb通过USB或wifi连接手机
2019-03-11
包装类
2019-03-11
JDK9-15新特性
2019-03-11
集合继承结构
2019-03-11
LinkedList 实现类
2019-03-11
Vector 实现类
2019-03-11
HashMap类、HashSet
2019-03-11
HashTable类
2019-03-11
TreeSet、TreeMap
2019-03-11
JVM内存模型
2019-03-11
反射机制
2019-03-11