src/world/usr.bin/42/src/42.c

90 lines
2.5 KiB
C

/*
*----------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <jeang3nie@HitchHiker-Linux.org> wrote this file. As long as you
* retain this notice you can do whatever you want with this stuff. If
* we meet some day, and you think this stuff is worth it, you can buy
* me a beer in return.
* ---------------------------------------------------------------------
* ______ _______ _ _________
* ( __ \ ( ___ )( ( /|( )\__ __/
* | ( \ )| ( ) || \ ( ||/ ) (
* | | ) || | | || \ | | | |
* | | | || | | || (\ \) | | |
* | | ) || | | || | \ | | |
* | (__/ )| (___) || ) \ | | |
* (______/ (_______)|/ )_) )_(
*
* _______ _______ _ _________ _______
* ( ____ )( ___ )( \ /|\__ __/( ____ \
* | ( )|| ( ) || \ ( | ) ( | ( |/
* | (____)|| (___) || \ | | | | | |
* | _____)| ___ || (\ \) | | | | |
* | ( | ( ) || | \ | | | | |
* | ) | ) ( || ) \ |___) (___| (____|\
* |/ |/ \||/ \_)\_______/(_______/
*
*/
#define _GNU_SOURCE
#include <dirent.h> // opendir, rewinddir, readdir
#include <stdio.h> // fopen, fclose, fwrite
#include <stdlib.h> // exit, srand
#include <string.h> // strncat, strcmp, strdup
#include <time.h> // time
#include "config.h"
int main(int argc, char *argv[]) {
int n = 0, i = 0;
DIR *d;
struct dirent *dir;
d = opendir(datadir);
// Determine the number of files
while ((dir = readdir(d)) != NULL) {
n++;
}
rewinddir(d);
char *filesList[n - 2]; // subtract two because of . and ..
// Put file names into the array
while ((dir = readdir(d)) != NULL) {
if (strcmp(dir->d_name, ".") && strcmp(dir->d_name, "..")) {
filesList[i] = strdup(dir->d_name);
i++;
}
}
rewinddir(d);
char *data = strdup(datadir);
time_t t;
srand((unsigned)time(&t));
int m = rand() % n;
strncat(data, filesList[m], 4);
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t nread;
// Open file
fp = fopen(data, "r");
if (fp == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
// Read contents from file
while ((nread = getline(&line, &len, fp)) != -1) {
fwrite(line, nread, 1, stdout);
}
free(line);
fclose(fp);
return 0; // I am still considering changing this to 42
}