Страница 1 из 1
Запись данных в файл
Добавлено: 08 июн 2024, 23:39
ya
Код: Выделить всё
#include <fstream>
#include <iostream>
int main() {
// Создаем объект класса ofstream для записи данных в файл
std::ofstream outputFile("output.txt");
if (outputFile.is_open()) {
// Записываем данные в файл
outputFile << "Hello, world!" << std::endl;
outputFile << 12345 << std::endl;
outputFile << 3.14159 << std::endl;
// Закрываем файл
outputFile.close();
std::cout << "Data has been written to file 'output.txt'" << std::endl;
} else {
std::cerr << "Error opening file for writing" << std::endl;
}
return 0;
}
Re: Запись данных в файл
Добавлено: 08 июн 2024, 23:43
ya
Этот код создаст файл с именем в формате file_год-месяц-день_час-минута-секунда.txt, например file_2022-01-11_15-30-45.txt.
Код: Выделить всё
#include <iostream>
#include <fstream>
#include <ctime>
#include <sstream>
int main() {
// Получаем текущую дату и время
time_t now = time(0);
struct tm *timeinfo;
char buffer[80];
timeinfo = localtime(&now);
strftime(buffer, 80, "%Y-%m-%d_%H-%M-%S", timeinfo);
// Создаем имя файла
std::stringstream filename;
filename << "file_" << buffer << ".txt";
// Создаем файл
std::ofstream file(filename.str());
if (file.is_open()) {
file << "This file was created at: " << buffer << std::endl;
file.close();
std::cout << "File created successfully: " << filename.str() << std::endl;
} else {
std::cerr << "Error creating file" << std::endl;
}
return 0;
}