LoginSignup
0
0

指定バイトのランダムワードを出力するツールプログラム

Posted at

1GBのランダムな単語が羅列させた改行なしのテストデータを作れやって突然言われたので、bashで作ってみたはいいけど処理が遅すぎて使いものにならない。

そんなわけでC言語にて、作りなおしたのがこちらです。

動作させるには、linuxだと
gcc -o create_data create.c
とかでコンパイルしてもらって

実行は、
./create_data 500000 hogehgoe.txt
みたいな感じです。

create_data.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// 単語のリストを定義
const char* word_list[] = {
    "apple", "banana", "cherry", "date", "elderberry",
    "fig", "grape", "honeydew", "kiwi", "lemon"
};

// 出力ファイルのパスを定義
const char* output_file = "output.txt";

int main(int argc, char* argv[]) {
    if (argc != 3) {
        printf("使用法: %s <limit_file_size_in_bytes> <output_file>\n", argv[0]);
        return 1;
    }

    long limit_file_size = atol(argv[1]);
    const char* output_file = argv[2]; // ここで再度 output_file を指定

    FILE* file = fopen(output_file, "a");
    if (file == NULL) {
        perror("ファイルを開く際のエラー");
        return 1;
    }

    // 現在のファイルサイズを初期化
    long current_file_size = 0;

    // 乱数ジェネレータを初期化
    srand(time(NULL));

    // 出力ファイルを追記モードで開く
    while (current_file_size < limit_file_size) {
        // リストからランダムに単語を選択
        int random_index = rand() % (sizeof(word_list) / sizeof(word_list[0]));
        const char* selected_word = word_list[random_index];

        // 改行なしで選択した単語をファイルに書き込む
        fprintf(file, "%s", selected_word);

        // 現在のファイルサイズを更新
        fseek(file, 0, SEEK_END);
        current_file_size = ftell(file);
    }

    // ファイルを閉じる
    fclose(file);

    // 成功メッセージを表示
    printf("単語が %s に正常に追加されました。現在のファイルサイズ: %ld バイト。\n", output_file, current_file_size);

    return 0;
}

1GBの出力で、だいたい2分ちょいです(環境によりけり)
ご利用は自己責任にてお願いします。

(了)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0