How to create a list of random file names, including extension, dates, and file size in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// Function to generate a random string of given length
void generateRandomString(char *buffer, size_t length) {
    const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    size_t charsetSize = sizeof(charset) - 1;

    for (size_t i = 0; i < length; i++) {
        buffer[i] = charset[rand() % charsetSize];
    }
    buffer[length] = '\0'; // Null-terminate
}

// Function to generate a random date
void generateRandomDate(char *buffer, size_t size) {
    int year  = rand() % 21 + 2000; // Random year between 2000 and 2020
    int month = rand() % 12 + 1;    // Random month between 1 and 12
    int day   = rand() % 28 + 1;    // Random day between 1 and 28

    snprintf(buffer, size, "%04d-%02d-%02d", year, month, day);
}

// Function to generate a random file size
size_t generateRandomFileSize() {
    return (rand() % 100000) + 1; // Random file size between 1 and 100000 bytes
}

int main() {
    srand((unsigned int)time(NULL)); // Seed RNG

    const char *extensions[] = {".txt", ".jpg", ".png", ".cpp", ".pdf"};
    size_t extCount = sizeof(extensions) / sizeof(extensions[0]);

    size_t numberOfFiles = 10;
    size_t fileLength = 9;

    char nameBuffer[64] = "";
    char dateBuffer[32] = "";

    for (size_t i = 0; i < numberOfFiles; i++) {
        generateRandomString(nameBuffer, fileLength);
        const char *ext = extensions[rand() % extCount];
        generateRandomDate(dateBuffer, sizeof(dateBuffer));
        size_t fileSize = generateRandomFileSize();

        printf("%s%s %s %zu bytes\n", nameBuffer, ext, dateBuffer, fileSize);
    }

    return 0;
}



/*
run:

BPZ3JAH7u.txt 2008-12-23 494 bytes
QJch2hlC5.jpg 2015-12-07 77239 bytes
st6S6WLFk.jpg 2014-09-15 25197 bytes
0dAGMALDH.png 2015-03-21 75428 bytes
m0lEhhmd3.txt 2009-05-24 74620 bytes
GmkwnK0X8.cpp 2003-09-19 37509 bytes
6EnisyLzF.pdf 2000-10-26 23619 bytes
BA45KesXM.pdf 2004-11-09 24378 bytes
eW79oifGG.png 2015-03-25 75090 bytes
x9rWzjRan.png 2012-04-19 47351 bytes

*/

 



answered 21 hours ago by avibootz

Related questions

...