{"id":1583,"date":"2015-10-10T00:01:31","date_gmt":"2015-10-10T07:01:31","guid":{"rendered":"http:\/\/c-for-dummies.com\/blog\/?p=1583"},"modified":"2015-10-03T09:08:27","modified_gmt":"2015-10-03T16:08:27","slug":"reading-a-file-randomly","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=1583","title":{"rendered":"Reading a File Randomly"},"content":{"rendered":"<p>Random file access isn&#8217;t about generating a random value and then reading at that position in the file. While you could do that, the term <em>random access<\/em> refers to file access that isn&#8217;t sequential. I suppose they could have called it <em>dynamic file access<\/em>, but I was only 8-years-old when computer scientists developed these concepts, so my input would not have been welcome.<br \/>\n<!--more--><br \/>\nAssume that you have a file consisting of formatted data. The data could be written as a series of structures or simply as a collection of similarly-sized variables, such as a series of integers.<\/p>\n<p>For this Lesson, I&#8217;m using a file of high scores named <code>high_scores.dat<\/code>. The file consists of 10 integer values (binary, not text) representing high scores stored largest values first, as in the rank of high scores. <a href=\"http:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2015\/09\/1010_.c\">Click here<\/a> to view the code I used to create this file. (WordPress won&#8217;t let me upload the raw data because a binary file is considered a security risk.)<\/p>\n<p>To read the entire file, front to back or sequentially, you can use the following code:<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\nint main()\r\n{\r\n    FILE *fh;\r\n    int x,score;\r\n\r\n    fh = fopen(\"high_scores.dat\",\"r\");\r\n    if( fh == NULL)\r\n    {\r\n        perror(\"Unable to read file\\n\");\r\n        return(1);\r\n    }\r\n    for(x=0;x&lt;10;x++)\r\n    {\r\n        fread(&score,sizeof(int),1,fh);\r\n        printf(\"%2d: %d\\n\",x+1,score);\r\n    }\r\n\r\n    fclose(fh);\r\n\r\n    return(0);\r\n}<\/pre>\n<p>The <em>fread()<\/em> function at Line 16 fetches an integer value into the variable <code>score<\/code>. The number of bytes read is set by <code>sizeof(int)<\/code>, and the value 1 directs the <em>fread()<\/em> function to read only one chunk of data. That value is displayed in Line 17.<\/p>\n<p>Here&#8217;s the sample output:<\/p>\n<pre><code> 1: 3333360\r\n 2: 2990950\r\n 3: 2760010\r\n 4: 2525080\r\n 5: 2186670\r\n 6: 1980000\r\n 7: 1976830\r\n 8: 1873420\r\n 9: 1363600\r\n10: 1248910<\/code><\/pre>\n<p>Those are the high scores, and that&#8217;s how binary data is read from a file, which is covered in my C programming books.<\/p>\n<p>Suppose you wanted to know only the sixth highest score, which is 1,980,000. A number of solutions exist to solve that puzzle.<\/p>\n<p>For example, you could read the file&#8217;s data into an array and then pluck out the fifth element (which is the sixth highest score). For my solution, I&#8217;ll use the <em>fseek()<\/em> function to specifically locate the 6th record and read only it. Here&#8217;s the source code:<\/p>\n<pre class=\"screen\">\r\n#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    FILE *fh;\r\n    int score;\r\n\r\n    fh = fopen(\"high_scores.dat\",\"r\");\r\n    if( fh == NULL)\r\n    {\r\n        perror(\"Unable to read file\\n\");\r\n        return(1);\r\n    }\r\n    fseek(fh,sizeof(int)*5,SEEK_SET);\r\n    fread(&score,sizeof(int),1,fh);\r\n    printf(\" 6: %d\\n\",score);\r\n\r\n    fclose(fh);\r\n\r\n    return(0);\r\n}<\/pre>\n<p>The <em>fseek()<\/em> function at Line 14 sets the file position indicator to a location the size of five integer values from the start of the file (<code>SEEK_SET<\/code>). That would be the location of the sixth integer written to the file, which is the value desired. In Line 15, a single integer value is read and stored in the <code>score<\/code> variable. Line 16 displays that value:<\/p>\n<pre><code> 6: 1980000<\/code><\/pre>\n<p>You could modify the code further. For example, prompt the user to input which high score value they want to see, then read the file to fetch only that single value. Thanks to the <em>fseek()<\/em> function and random file access, you don&#8217;t need to churn through the entire file just to get that result.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The <em>fseek()<\/em> function can fetch a specific chunk of info from a file. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=1583\">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-1583","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\/1583","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=1583"}],"version-history":[{"count":4,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1583\/revisions"}],"predecessor-version":[{"id":1599,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1583\/revisions\/1599"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1583"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1583"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1583"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}