{"id":1259,"date":"2021-01-21T17:26:56","date_gmt":"2021-01-21T17:26:56","guid":{"rendered":"https:\/\/blog.samarthya.me\/wps\/?p=1259"},"modified":"2021-01-21T17:26:58","modified_gmt":"2021-01-21T17:26:58","slug":"files-golang","status":"publish","type":"post","link":"https:\/\/blog.samarthya.me\/wps\/2021\/01\/21\/files-golang\/","title":{"rendered":"Files: GoLang"},"content":{"rendered":"<p>Learning a new syntax and the libraries is always a task, and the only way forward is gradual. In this blog I will try to create a small program to read a text file and will keep updating the program to include more sophistication<\/p>\n\n\n<figure class=\"wp-block-pullquote is-style-solid-color\"><blockquote><p>I will not talk about packages, code organization. If required please look at my previous blogs which cover them in detail.<\/p><\/blockquote><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Code: File<\/h2>\n\n\n\n<p>I will give you the complete code and then explain what all I have done<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package files\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc message(m string) {\n\tlog.Printf(\" FILES: %s\", m)\n}\n\n\/\/ ReadFile reads the file and dump contents\nfunc ReadFile(fn string) {\n\tmessage(\"ReadFile Invoked\")\n\tfh, err := os.OpenFile(fn, os.O_RDONLY, 0666)\n\n\tif err != nil {\n\t\tmessage(\" Unable to open file \" + fn)\n\t\tos.Exit(1)\n\t}\n\n\tdefer fh.Close()\n\tdefer message(\" Closing the handle\")\n\n\tfr := bufio.NewReader(fh)\n\tfor {\n\t\tli, err := fr.ReadString('\\n')\n\t\tif err == nil {\n\t\t\tfmt.Printf(\" >&lt;: %s\", li)\n\t\t\tcontinue\n\t\t} else if err == io.EOF {\n\t\t\tfmt.Println(\" --- End of File ---\")\n\t\t\tbreak\n\t\t}\n\t\tfmt.Println(\" Error:\", err)\n\t\tbreak\n\n\t}\n\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Step 1: Define the package<\/h2>\n\n\n\n<p>I keep the logic separate form the <code>main<\/code> package as a habit, and continuing the trend; I define a package <code>files<\/code> here.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package files<\/code><\/pre>\n\n\n\n<p><code>imports <\/code>will be explained later, but lets define a helper function &#8211; <code>message<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 2: Function <code>message<\/code><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>func message(m string) {\n\tlog.Printf(\" FILES: %s\", m)\n}<\/code><\/pre>\n\n\n\n<p>The primary purpose of this is printing a debug message with a predefined prefix <code>FILES:<\/code><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>2021\/01\/21 18:46:30  FILES: ReadFile Invoked<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Step 3: Function <code>ReadFile<\/code><\/h2>\n\n\n\n<p>Let&#8217;s write the function that will read the actual file which will be passed as an argument.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>Invoking this function is as easy as importing the <code>package<\/code> and calling <code>files.ReadFile<\/code><\/p><\/blockquote>\n\n\n\n<h3 class=\"wp-block-heading\">Arguments: fn &#8211; <code>FileName<\/code><\/h3>\n\n\n\n<p>The <code>ReadFile<\/code> shall take an argument the <code>file-name<\/code> that needs to be read for contents. The objective of this function is simple &#8211; Dump everything on the STDOUT.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">package <code>os<\/code> &#8211; <a href=\"https:\/\/golang.org\/pkg\/os\/\">Link<\/a><\/h3>\n\n\n\n<p>Package <code>os<\/code> allows a platform independent interface to Operating System functionality and hence the name O.S.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Function &#8211; <a href=\"https:\/\/golang.org\/pkg\/os\/#OpenFile\">OpenFile<\/a><\/h3>\n\n\n\n<p>The primary function we will be using the <code>OpenFile<\/code>. It opens the specified name with the specified flags.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fh, err := os.OpenFile(fn, os.O_RDONLY, 0666)<\/code><\/pre>\n\n\n\n<p>The official documentation defines the signature of the function as <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func OpenFile(name string, flag int, perm FileMode) (*File, error)<\/code><\/pre>\n\n\n\n<p>Returning the FileHandle &#8211; <code>fh<\/code> and in case of error <code>err<\/code>.<\/p>\n\n\n\n<p>More about the <code>File<\/code> can be found <a href=\"https:\/\/golang.org\/src\/os\/types.go?s=369:411#L6\">here<\/a>.<\/p>\n\n\n\n<p>Check for error which can indicate file open was failure.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if err != nil {\n\tmessage(\" Unable to open file \" + fn)\n\tos.Exit(1)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Example: <code>readme1.txt<\/code><\/h3>\n\n\n\n<p>In case the file doesn&#8217;t exists the error message as below can be seen<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>2021\/01\/21 22:45:04  FILES:  Unable to open file readme1.txt<\/code><\/pre>\n\n\n\n<p>A deferred call to <a href=\"https:\/\/golang.org\/pkg\/os\/#File.Close\">close<\/a> the file. Which shall render the <code>fh<\/code> useless for <code>io<\/code> operation.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>defer fh.Close()\ndefer message(\" Closing the handle\")<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">ReadContents: BufferedReader<\/h3>\n\n\n\n<p>After opening the file it is time to read the contents, for this we will use a <code><a href=\"https:\/\/golang.org\/pkg\/bufio\/\">bufio<\/a><\/code> package.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><a href=\"https:\/\/golang.org\/pkg\/bufio\/#NewReader\">NewReader<\/a><\/h4>\n\n\n\n<p>Using the filehandle &#8211; <code>fh<\/code> lets create a reader <code>fr<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fr := bufio.NewReader(fh)<\/code><\/pre>\n\n\n\n<p>Ideally you should check for <code>nil<\/code> before you proceed to reading the contents. I am using the <code><a href=\"https:\/\/golang.org\/pkg\/bufio\/#Reader.ReadString\">ReadString<\/a><\/code> from the reader.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func (b *Reader) ReadString(delim byte) (string, error)<\/code><\/pre>\n\n\n\n<p>It will read till the occurrence of the first newline (delimiter)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>li, err := fr.ReadString('\\n')<\/code><\/pre>\n\n\n\n<p>rest of the code is quite simple that processes<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Checking error for the invocation of <code>ReadString<\/code><\/li><li>If no error &#8211; dump the contents on stdout<\/li><li>In case of error check if it is <code>EOF<\/code><\/li><li>Else, show the nature of error and break out of the <code>for<\/code> loop.<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>if err == nil {\n\tfmt.Printf(\" >&lt;: %s\", li)\n\tcontinue\n} else if err == io.EOF {\n\tfmt.Println(\" --- End of File ---\")\n\tbreak\n}\nfmt.Println(\" Error:\", err)\nbreak<\/code><\/pre>\n\n\n\n<h2 class=\"has-text-align-center wp-block-heading\">&#8212; THE END &#8212; <\/h2>\n","protected":false},"excerpt":{"rendered":"<p>Learning a new syntax and the libraries is always a task, and the only way forward is gradual. In this blog I will try to create a small program to read a text file and will keep updating the program to include more sophistication I will not talk about packages, code organization. If required please [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":1261,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"image","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"footnotes":""},"categories":[137,34],"tags":[143,23],"class_list":["post-1259","post","type-post","status-publish","format-image","has-post-thumbnail","hentry","category-golang","category-technical","tag-files","tag-golang","post_format-post-format-image"],"_links":{"self":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/1259","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/comments?post=1259"}],"version-history":[{"count":0,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/1259\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media\/1261"}],"wp:attachment":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media?parent=1259"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/categories?post=1259"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/tags?post=1259"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}