Dave's Brain

Browse - Programming Tips - How do I efficiently do what the "touch" command does?

Date: 2008feb20
Language: C/C++


Q.  How do I efficiently do what the "touch" command does?

A.  Use utime() if the file exists, otherwise create the file.
Like this:

static bool create(const char *filename) { FILE *f; if ((f = fopen(filename, "wb")) == NULL) { fprintf(stderr, "Cannot create %s because %s\n", filename, _strerror(NULL)); return false; } fclose(f); return true; } bool touch(const char *filename) { struct utimbuf times; // utime(,NULL) is supposed to set the current time but doesn't // on every platform memset(&times, '\0', sizeof(times)); times.actime = times.modtime = time(NULL); if (utime(filename, &times) == 0) return true; return create(filename); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.