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(×, '\0', sizeof(times)); times.actime = times.modtime = time(NULL); if (utime(filename, ×) == 0) return true; return create(filename); }
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: