In: Computer Science
please submit the C code( no third party library). the C code will create output to a file, and iterate in a loop 60 times and each iteration is 1 second, and if any key from your keyboard is pressed will write a 1 in the file, for every second no key is pressed, will write a 0 into the output file.
The following code is written in C language in which I have considered if any keyboard hit occurs in 1 second time period then we will write 1 in the output file but skip the remaining second. This is well explained in the comments.
// Library imported
#include<stdio.h>
#include<string.h>
#include<time.h>
//Time delay function for 1 second delay
int delay(int number_of_seconds)
{
clock_t start_time = clock();
// 1000*number_of_seconds converts second to milliseconds
// while loop will work for 1 second time period
while (clock() < start_time + 1000 * number_of_seconds)
{
// kbhit is used to check keyboard hits
if(kbhit())
{
char ch='\0';
ch=_getche();
//once keyboard button is pressed we take it as input
// and store it in temporary varaible
// _getche is used to avoid pressing enter after some character
printf("\r\n");
// Just to make console screen proper previous line used
return 1;
// if any keyboard hits in 1 second peroid we will return 1
}
}
return 0;
// if no keyboard hit in 1 second peroid we will return 0
}
int main( )
{
FILE *filePointer ;
// declaring filePointer
filePointer = fopen("output.txt", "w") ;
// opening file named output.txt it will always be empty in begining
if ( filePointer == NULL )
{
// if some exception occurs
printf( "Failed to open" ) ;
}
else
{
int i;
// 60 seconds loop start
for (i = 0; i < 60; i++) {
printf("%d iteration\r\n",i+1);
// printing every iteration so you can keep track on time
int s=delay(1);
if(s==0){
fputs("0", filePointer) ;
// write 0 in file if delay fn returns 0
}
else{
fputs("1", filePointer) ;
// write 1 in file if delay fn returns 1
}
}
fclose(filePointer) ;
// close the file
printf("End of the Code") ;
//end of the code
}
return 0;
}
You can also change some part of code to make different implementations.
If any doubts feel free to ask
Thanks