C++ 获取当前的时间并储存于ofs
时间: 2023-06-29 21:17:44 浏览: 51
您可以使用 C++ 标准库中的 localtime 和 strftime 函数获取当前时间,并将其存储到指定的文件中。以下是示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <ctime>
int main() {
// 获取当前时间
std::time_t now = std::time(nullptr);
std::tm* timeinfo = std::localtime(&now);
// 格式化时间字符串
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
// 将时间字符串写入文件
std::ofstream ofs("time.txt");
ofs << buffer << std::endl;
ofs.close();
return 0;
}
```
以上代码会将当前时间保存到 time.txt 文件中。您可以根据需要修改时间格式和文件名。
相关问题
Mac C++代码: 取得当下的时间,将其转换为以年月日排序的8个数字,并且储存于ofs
下面是一个获取当前时间并将其转换为按年月日排序的8个数字并保存到文件的C++代码示例:
```c++
#include <iostream>
#include <fstream>
#include <chrono>
int main() {
// 获取当前时间
auto now = std::chrono::system_clock::now();
std::time_t t = std::chrono::system_clock::to_time_t(now);
// 将时间转换为按年月日排序的8个数字
std::tm tm = *std::localtime(&t);
int year = tm.tm_year + 1900;
int month = tm.tm_mon + 1;
int day = tm.tm_mday;
int hour = tm.tm_hour;
int minute = tm.tm_min;
int second = tm.tm_sec;
int millisecond = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count() % 1000;
// 将8个数字保存到文件
std::ofstream ofs("time.txt");
ofs << year << month << day << hour << minute << second << millisecond;
ofs.close();
return 0;
}
```
这个示例中,我们使用了C++11的`std::chrono`库来获取当前时间。首先,我们获取了当前时间的`system_clock`类型,然后通过`std::chrono::system_clock::to_time_t`函数将其转换为`std::time_t`类型,以便将其转换为年月日格式。接下来,我们使用了`std::localtime`函数将时间转换为本地时间。最后,我们将年月日、时分秒和毫秒数保存到文件中。
C++中fstream类对象,获取当前偏移量
你可以使用`tellg()`函数获取`fstream`类对象当前的读指针位置,或者使用`tellp()`函数获取当前的写指针位置。例如:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream ofs("test.txt", ios::app);
ofs << "Hello, World!" << endl;
// 获取写指针位置
streampos pos = ofs.tellp();
cout << "当前写指针位置:" << pos << endl;
ofs.close();
ifstream ifs("test.txt");
string line;
getline(ifs, line);
// 获取读指针位置
pos = ifs.tellg();
cout << "当前读指针位置:" << pos << endl;
ifs.close();
return 0;
}
```
输出结果为:
```
当前写指针位置:13
当前读指针位置:0
```