Skip to content

Instantly share code, notes, and snippets.

@FelicitusNeko
Last active May 28, 2024 00:52
Show Gist options
  • Select an option

  • Save FelicitusNeko/3b991bc675c0da5b476d2b420cd0c7fe to your computer and use it in GitHub Desktop.

Select an option

Save FelicitusNeko/3b991bc675c0da5b476d2b420cd0c7fe to your computer and use it in GitHub Desktop.
Shuffles and outputs a list of .txt files in the pwd.
// TXT Shuffler by FelicitusNeko is marked with CC0 1.0.
// To view a copy of this license, visit https://creativecommons.org/publicdomain/zero/1.0/
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct listing_t {
char *name;
struct listing_t *next;
} LISTING;
int main(void) {
struct dirent *de;
DIR *dr = opendir(".");
LISTING *item = NULL;
int count = 0;
if (dr == NULL)
{
printf("Could not open current directory\n");
return 1;
}
while ((de = readdir(dr)) != NULL) {
//// Following two lines work in Linux but not Windows.
// if (de->d_type != DT_REG) continue;
// size_t namelen = strlen(de->d_name);
size_t namelen = de->d_namlen;
if (namelen < 4) continue;
if (strncmp(&de->d_name[namelen - 4], ".txt", 4)) continue;
if (!strncmp(de->d_name, "LIST__", 6)) continue;
LISTING *newitem = malloc(sizeof(LISTING));
newitem->name = malloc(sizeof(char) * namelen + 2);
strncpy(newitem->name, de->d_name, namelen + 1);
newitem->next = item;
item = newitem;
count++;
}
closedir(dr);
if (item == NULL) {
printf("No items in list\n");
return 2;
}
time_t t = time(NULL);
struct tm *lt = localtime(&t);
char listfile[33] = {0};
snprintf(listfile, 32, "LIST__%d_%02d_%02d__%02d_%02d_%02d.txt",
lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec);
FILE *listfile_h = fopen(listfile, "w");
srand(t);
while (item != NULL) {
int getitem = rand() % count;
LISTING *delitem = item;
if (getitem == 0) {
item = item->next;
} else {
for (int x = 1; x < getitem; x++){
delitem = delitem->next;
}
LISTING *previtem = delitem;
delitem = delitem->next;
previtem->next = delitem->next;
}
fprintf(listfile_h, "%s\n", delitem->name);
free(delitem->name);
free(delitem);
count--;
}
fclose(listfile_h);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment