Programming Tips - C/C++: How to efficiently do what the "touch" command does

Date: 2008feb20 Update: 2026sep30 Language: C/C++ Q. C/C++: How to efficiently do what the "touch" command does A. Use utime() if the file exists, otherwise create the file. Like this:
#include <utime.h> bool touch(const char *filename) { struct utimbuf times = {}; // utime(,NULL) is supposed to set the current time but doesn't on every platform // so we have to get the current time. times.actime = times.modtime = time(NULL); if (utime(filename, &times) == 0) return true; return create(filename); }
Full Example Use:
#include <utime.h> #include <time.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <sys/stat.h> bool create(const char *filename) { FILE *f; if ((f = fopen(filename, "wb")) == NULL) { fprintf(stderr, "Cannot create %s because %s\n", filename, strerror(errno)); return false; } fclose(f); return true; } // (Place touch() from above here) int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: touch <filename>\n"); exit(1); } const char *filename = argv[1]; struct stat sb; if (stat(filename, &sb) == 0) { printf("File %s exists -- touching it\n", filename); touch(filename); } else { printf("File %s is missing -- creating it\n", filename); create(filename); if (stat(filename, &sb) == 0) { printf("Now %s exists -- correct\n", filename); } else { printf("Now %s is still missing -- problem\n", filename); } } }
Output:
File newfile.dat is missing -- creating it Now newfile.dat exists -- correct