一、函式功能
將得到的資料輸出到指定路徑檔案內
二、代碼
#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;
}
三、代碼講解
-
_getcwd(buffer, MAX_PATH);
1)函式功能:獲取檔案的當前路徑,
2)在Windows VS2017環境下,頭檔案是#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));得到當前時間:年-月-日 時-分-秒 -
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 -
在回圈里面,將資料a、b儲存在檔案
test_joint_2020-11-03 09-42-29.txt中 -
test_value.close();關閉檔案
四、列印結果
-
運行之后,結果為:

-
檔案路徑:

-
檔案內容:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/202682.html
標籤:其他
