Skip to content

Instantly share code, notes, and snippets.

@szaydel
Last active July 5, 2022 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szaydel/b43a53c461b1cf6ea903d224b2cd3747 to your computer and use it in GitHub Desktop.
Save szaydel/b43a53c461b1cf6ea903d224b2cd3747 to your computer and use it in GitHub Desktop.
This utility is useful for cases where a really large number of files needs to be created, and the cost of loops in bash or some other shell is prohibitively high.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
int touch_file(const char *prefix, const char *suffix, size_t index) {
char filename[1024] = {0};
strncpy(filename, prefix, strlen(prefix));
char *end = &filename[0] + strlen(prefix);
int n = sprintf(end, "%zd", index);
if (n < 0) {
return -1;
}
end += n;
sprintf(end, ".%s", suffix);
mode_t touch_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
int fd = open(filename, O_RDWR | O_CREAT, touch_mode);
if (fd < 0) {
return fd;
}
return close(fd);
}
int main (int argc, char **argv) {
int opt;
char *prefix;
char *suffix;
long long nfiles = 0;
while ((opt = getopt(argc, argv, "n:p:s:")) != -1) {
switch (opt) {
case 'n':
nfiles = strtoll(optarg, NULL, 10);
if (nfiles < 0) {
nfiles = -nfiles;
}
break;
case 'p':
prefix = optarg;
break;
case 's':
suffix = optarg;
break;
default: /* '?' */
fprintf(stderr, "Usage: %s <-c nfiles> <-p prefix> <-s suffix>\n",
argv[0]);
exit(EXIT_FAILURE);
}
}
for (size_t i = 0; i < (size_t)nfiles; i++) {
int ret = 0;
if ((ret = touch_file(prefix, suffix, i)) < 0) {
fprintf(stderr, "touch_file returned: %d\n", ret);
perror("touch_file");
exit(EXIT_FAILURE);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment