Dave's Brain

Browse - programming tips - efficient touch

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, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.