LoginSignup
0
0

More than 1 year has passed since last update.

Pythonで簡単なc言語のファイルを作成

Last updated at Posted at 2021-10-26

たくさんのバイナリファイルを作るにあたりc言語のプログラムファイルが必要だったのでPythonでチャチャチャと作った。その回顧録です。

c言語のプログラムファイルを作成

数値計算を含まない

文字列をprintfするだけのC言語ファイルを100個作るものです。
文字列は、英字の大文字・小文字を5~100文字をランダムに生成したものです。

strmakefile.py
from random import randint
x_lay = "abcdefghijklmopqrstuvwxyz"
X_lay = str.upper(x_lay)
lay = x_lay + X_lay
laylist = list(lay)
#print(laylist)
#['a', 'b', 'c', 'd'....

for i in range(100):
    str = ""
    strlen = randint(5, 100)
    for k in range(strlen):
        t = randint(0, 45)
        str += laylist[t]

    txt = "#include <stdio.h> \nint main(void){\nprintf(\""
    txt = txt+str+"\");\n}"
    filename = f"hoge/hoge{i}.c"
    with open(filename, mode="w") as f:
        s = f.write(txt)

これを変数strの生成を行っているところでinputを使うとキーボードで入力したものが表示されるプログラムファイルが作成できる。

数値計算を含む

これは数値計算をするC言語のプログラムファイルを100個作るものです。
変数txにそれぞれ[a,b,c,d,e]に数値を入れています。
for文でランダムな数字を生成してその長さの式が生成されます。

nummakefile.py
import random
txt = "#include <stdio.h> \nint main(void){\n"
tx = "int a = 2;\nint b = 3;\nfloat c = 2.34;\nfloat d = 5.98;\nint e = 100;\nfloat x = "
entxt = "\n}"
numlen = ["+","-","*","/"]
var = ["a", "b", "c", "d", "e"]
eof = ";"
for i in range(100):
    m = random.randint(1, 10)
    oppo = txt + tx
    for k in range(m):
        oppo += random.choice(var)
        oppo += random.choice(numlen)
    oppo += random.choice(var)
    oppo += eof + entxt
    filename = f"hoge/hoge{i}.c"
    with open(filename, mode="w") as f:
        f.write(oppo)

コンパイル

まとめてコンパイルする時は、for文を使うといいかも‼

lsの-1オプションでファイル名だけを1行ずつ表示してくれる。
呼び出されたファイル名を変数iに入れてコンパイルする。この時に-oオプションがないと同じバイナリファイルを上書きしていくだけなで、変数iを使ってそれぞれ違う名前のファイルを作成していく。

for i in `ls -1 *.c`
do
 gcc $i -o con$i
done
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