Home » Code Snippets » C/C++ Code Snippets

C++ program to write and read time in/from binary file using fstream

In this program we will learn how to write and read time in/from binary file using fstream in c++ programming language?

There will be two functions

  • writeTime() - that will write time into the file
  • readTime() - that will read time from the file

In this program, there are two things to be noticed, how time will be formatted into a string (using sprintf) and how time values will be extracted from the string (using sscanf).

Program to write, read time in,from binary file in C++

#include <iostream>
#include <fstream>
#include <iomanip> //for setfill() and setw()

using namespace std;

#define FILE_NAME "time.dat"

//function to write time into the file
void writeTime(int h, int m, int s){	
	char str[10];
	fstream file;
	file.open(FILE_NAME, ios::out|ios::binary);

		cout<<"Error in creating file!!!"<<endl;

	//make string to write

	//write into file
	cout<<"Time "<<str<<" has been written into file."<<endl;
	//close the file

//function to read time from the file
void readTime(int *h,int *m, int *s){
	char str[10];
	int inH,inM,inS;

	fstream finC;
		cout<<"Error in file opening..."<<endl;
		//extract time values from the file
		//assign time into variables, which are passing in function

int main(){
	int m,h,s;
	cout<<"Enter time:\n";
	cout<<"Enter hour: "; 	cin>>h;
	cout<<"Enter minute: "; cin>>m;
	cout<<"Enter second: "; cin>>s;

	//write time into file
	//now, reset the variables
	//read time from the file 
	//print the time
	cout<<"The time is "<<setw(2)<<setfill('0')<<h<<":"<<setw(2)<<setfill('0')<<m<<":"<<setw(2)<<setfill('0')<<s<<endl;	
	return 0;


Enter time: 
Enter hour: 10
Enter minute: 15
Enter second: 5 
Time 10:15:05 has been written into file. 
The time is 10:15:05

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.