Write a program for the following man page : NAME mytouch - change the file time
ID: 3821956 • Letter: W
Question
Write a program for the following man page :
NAME
mytouch - change the file timestamps
SYNOPSIS
mytouch FILE [SECONDS]
DESCRIPTION
Update the access and modification times of FILE to the current time.
EXAMPLES
NOTES
Does not use any C++ specific code.
Does not prompt the user in any way.
Does not perform input validation.
HINTS
Search man pages for a function that makes it easy to get the current time. This is part of the assignment.
mytouch foo.txt sets the access and modification time of foo.txt to the current time iffoo.txt exists, creates it otherwise mytouch foo.txt 1000000 sets the seconds since the epoch of the access and
modification time of foo.txt to 1000000
Explanation / Answer
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <utime.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
const char *filename = argv[1];
FILE *fp = fopen(argv[1], "w");
close(fp);
int millis = time(NULL); /* set mtime to current time */
if (argc == 3)
{
millis = atoi(argv[2]);
}
struct stat foo;
time_t mtime;
struct utimbuf new_times;
stat(filename, &foo);
new_times.actime = millis; /* keep atime unchanged */
new_times.modtime = millis; /* set mtime to current time */
utime(filename, &new_times);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.