{"id":5579,"date":"2022-10-22T00:01:11","date_gmt":"2022-10-22T07:01:11","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=5579"},"modified":"2022-12-02T10:27:44","modified_gmt":"2022-12-02T18:27:44","slug":"a-nifty-random-number-trick","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=5579","title":{"rendered":"A Nifty Random Number Trick"},"content":{"rendered":"<p>I don&#8217;t believe I&#8217;ll ever absorb all the wondrous potential of Linux\/Unix. Case in point is the <code>\/dev\/random<\/code> file. It&#8217;s exactly what the name implies: random stuff. And you can use this nifty file in your C programs to generate random values.<br \/>\n<!--more--><br \/>\nAvailable in Linux, Unix, and macOS (sorry, Windows), the <code>\/dev\/random<\/code> file is classified as a special character file type. Its purpose is to generate random values. If you use the <em>cat<\/em> command to &#8220;view&#8221; it, you see garbage puke all over the terminal window; press Ctrl+C to halt the spew. (The random output can inadvertently mess with some terminal settings, so be careful.)<\/p>\n<p>According to the <a href=\"https:\/\/en.wikipedia.org\/wiki\/\/dev\/random\" rel=\"noopener\" target=\"_blank\">all-knowing Wikipedia<\/a>, the file uses &#8220;noise&#8221; from various device drivers to generate its random values. That&#8217;s good enough for me, and a reliable way on a *NIX box to obtain a random value, as shown in this code:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2022_10_22-Lesson-a.c\" rel=\"noopener\" target=\"_blank\">2022_10_22-Lesson-a.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\nint main()\r\n{\r\n    const char filename[] = \"\/dev\/random\";\r\n    FILE *dr;\r\n    int c;\r\n\r\n    dr = fopen(filename,\"r\");\r\n    if( dr )\r\n    {\r\n        c = fgetc(dr);\r\n        printf(\"Random value: %d\\n\",c);\r\n        fclose(dr);\r\n    }\r\n    return(0);\r\n}<\/pre>\n<p>The <code>\/dev\/random<\/code> file is declared as a string constant at Line 5. It&#8217;s a character file, so I use the stream oriented <em>fopen()<\/em> function at Line 9 to open it for reading. Upon success, the <em>if<\/em> statements execute, fetching a single character (<em>int<\/em> variable <code>c<\/code>) from the file and outputting it at Line 13. The file is closed at Line 14. Note that you don&#8217;t need to seed a randomizer to employ this technique.<\/p>\n<p>Here is the output:<\/p>\n<p><code>Random value: 169<\/code><\/p>\n<p>This update to the code reads ten values from the file:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2022_10_22-Lesson-b.c\" rel=\"noopener\" target=\"_blank\">2022_10_22-Lesson-b.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\nint main()\r\n{\r\n    const char filename[] = \"\/dev\/random\";\r\n    const int size = 10;\r\n    FILE *dr;\r\n    int c,x;\r\n\r\n    dr = fopen(filename,\"r\");\r\n    if( dr )\r\n    {\r\n        for( x=0; x&lt;size; x++ )\r\n        {\r\n            c = fgetc(dr);\r\n            printf(\"Random value: %d\\n\",c);\r\n        }\r\n        fclose(dr);\r\n    }\r\n    return(0);\r\n}<\/pre>\n<p>Constant <em>int<\/em> value <code>size<\/code> sets the number of integers to output. A <em>for<\/em> loop is added to fetch and output the ten values:<\/p>\n<p><code>Random value: 131<br \/>\nRandom value: 105<br \/>\nRandom value: 172<br \/>\nRandom value: 54<br \/>\nRandom value: 158<br \/>\nRandom value: 185<br \/>\nRandom value: 201<br \/>\nRandom value: 110<br \/>\nRandom value: 73<br \/>\nRandom value: 67<\/code><\/p>\n<p>To gobble all ten values into an array, I updated the code to use the <em>fread()<\/em> function to consume the array in a single gulp:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2022_10_22-Lesson-c.c\" rel=\"noopener\" target=\"_blank\">2022_10_22-Lesson-c.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\nint main()\r\n{\r\n    const char filename[] = \"\/dev\/random\";\r\n    const int size = 10;\r\n    FILE *dr;\r\n    int r[size];\r\n    int x;\r\n\r\n    dr = fopen(filename,\"r\");\r\n    if( dr )\r\n    {\r\n        fread(&amp;r,sizeof(int),size,dr);\r\n        for( x=0; x&lt;size; x++ )\r\n        {\r\n            printf(\"Random value: %d\\n\",r[x]);\r\n        }\r\n        fclose(dr);\r\n    }\r\n    return(0);\r\n}<\/pre>\n<p>Array <code>r[]<\/code> is declared at Line 8. The <em>fread()<\/em> function at Line 14 grabs the ten integers at once, setting them into the array. A <em>for<\/em> loop outputs the values; the output is similar to the preceding example.<\/p>\n<p>To read larger values, again I use the <em>fread()<\/em> function to procure an <em>unsigned long<\/em> integer value from the <code>\/dev\/random<\/code> file:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2022_10_22-Lesson-d.c\" rel=\"noopener\" target=\"_blank\">2022_10_22-Lesson-d.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\nint main()\r\n{\r\n    const char filename[] = \"\/dev\/random\";\r\n    FILE *dr;\r\n    unsigned long r;\r\n\r\n    dr = fopen(filename,\"r\");\r\n    if( dr )\r\n    {\r\n        fread(&amp;r,sizeof(unsigned long),1,dr);\r\n        printf(\"Random value: %lu\\n\",r);\r\n        fclose(dr);\r\n    }\r\n    return(0);\r\n}<\/pre>\n<p>The <em>fread()<\/em> function at Line 12 specifies the size of an <em>unsigned long<\/em> value, reading the value from open file <code>dr<\/code> and setting into variable <code>r<\/code>. Here is sample output:<\/p>\n<p><code>Random value: 15304796159533619025<\/code><\/p>\n<p>You can read real numbers as well. This code update consumes a <em>double<\/em> value from the <code>\/dev\/random<\/code> file:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2022_10_22-Lesson-e.c\" rel=\"noopener\" target=\"_blank\">2022_10_22-Lesson-e.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\nint main()\r\n{\r\n    const char filename[] = \"\/dev\/random\";\r\n    FILE *dr;\r\n    double r;\r\n\r\n    dr = fopen(filename,\"r\");\r\n    if( dr )\r\n    {\r\n        fread(&amp;r,sizeof(double),1,dr);\r\n        printf(\"Random value: %f\\n\",r);\r\n        fclose(dr);\r\n    }\r\n    return(0);\r\n}<\/pre>\n<p>The output here is interestingly whacky:<\/p>\n<p><code>Random value: -3581507666920258283702881838842193028636242448207<br \/>\n7114148082694520146327147739765556024935895227752040177045026700<br \/>\n73182756975969049482863570233961353096133083136.000000<\/code><\/p>\n<p>Do consider using this approach when your code needs a quick-and-dirty yet random value. This trick is yet another nifty thing about Linux and similar operating systems.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Generating random numbers without using the <em>rand()<\/em> function. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=5579\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-5579","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5579","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=5579"}],"version-history":[{"count":9,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5579\/revisions"}],"predecessor-version":[{"id":5670,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5579\/revisions\/5670"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=5579"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=5579"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=5579"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}