Write a program (in C) for the following man page : NAME mytouch - change the fi
ID: 3822357 • Letter: W
Question
Write a program (in C) 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
mytouch foo.txt
sets the access and modification time of foo.txt to the current time if
foo.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
NOTES
· Does not use any C++ specific code.
· Does not prompt the user in any way.
· Does not perform input validation.
mytouch foo.txt
sets the access and modification time of foo.txt to the current time if
foo.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.