{"id":4036,"date":"2020-03-21T00:01:28","date_gmt":"2020-03-21T07:01:28","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=4036"},"modified":"2020-05-16T08:10:58","modified_gmt":"2020-05-16T15:10:58","slug":"opening-a-file-in-the-raw","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=4036","title":{"rendered":"Opening a File in the Raw"},"content":{"rendered":"<p>The <em>fopen()<\/em> function opens a file or stream for formatted input. The &#8220;formatted&#8221; is where the function gets its <em>f<\/em> prefix, which I always thought stood for <em>file<\/em>. It doesn&#8217;t. The <em>fopen()<\/em> function is the formatted file (and stream) function, the <em>open()<\/em> function is for low-level, unformatted file access.<br \/>\n<!--more--><br \/>\nRare is the beginner book or tutorial that covers the <em>open()<\/em> function, primarily because it deals with low-level, unformatted file access and it&#8217;s not really required to open a file. Therefore, it&#8217;s skipped or glossed over. Yet, the function is worth some discovery.<\/p>\n<p>Before exploring the <em>open()<\/em> function, here&#8217;s an example of the <em>fopen()<\/em> function, which accesses the file <code><a href=\"https:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2015\/09\/gettysburg.txt\">gettysburg.txt<\/a><\/code> and sends its contents to standard output:<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\nint main()\r\n{\r\n    const char filename[] = \"gettysburg.txt\";\r\n    FILE *fp;\r\n    int ch;\r\n\r\n    fp = fopen(filename,\"r\");\r\n    if( fp==NULL )\r\n    {\r\n        fprintf(stderr,\"Unable to open %s\\n\",filename);\r\n        return(1);\r\n    }\r\n\r\n    while( !feof(fp) )\r\n    {\r\n        ch = fgetc(fp);\r\n        if( ch==EOF )\r\n            break;\r\n        fputc(ch,stdout);\r\n    }\r\n    fclose(fp);\r\n\r\n    return(0);\r\n}<\/pre>\n<p>The <em>fopen()<\/em> function&#8217;s arguments are a filename string and a string representing the opening mode. The value returned is a <em>FILE<\/em> pointer, a handle containing details and other trivia about the open file. Upon success, the file is opened for formatted input and output, depending upon the second argument.<\/p>\n<p>The <em>open()<\/em> function, on the other hand, offers a different definition. Prototyped in the <code>fnctl.h<\/code> header, here&#8217;s its <em>man<\/em> page (2) format:<\/p>\n<p><code>int open(const char *path, int oflag, <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=4125\">...<\/a>);<\/code><\/p>\n<p>The first argument (<code>const char *path<\/code>) is the same as <em>fopen()<\/em>, a filename string or the pathname to a device to open. The argument (<code>oflag<\/code>) is one or more constant expressions or flags that set how the file is to be opened. These constants, also defined in <code>fnctl.h<\/code>, must include one of these three:<\/p>\n<p><code>O_RDONLY<\/code> Open the file read-only.<br \/>\n<code>O_WRONLY<\/code> Open the file write-only.<br \/>\n<code>O_RDWR<\/code> Open the file for reading and writing.<\/p>\n<p>Additional flags set a specific file-opening mode and are logically OR&#8217;d with each other. For example, the <code>O_CREAT<\/code> flag creates a file that doesn&#8217;t exist; unlike the <em>fopen()<\/em> function, using <em>open()<\/em> on a file that doesn&#8217;t exist without specifying the <code>O_CREAT<\/code> flag returns an error.<\/p>\n<p>The third argument is documented differently, depending on the source. I have no idea what it does, but it&#8217;s not required for the examples on this blog.<\/p>\n<p>The <em>open()<\/em> function returns a non-negative integer value, a file descriptor. Upon failure, the value -1 is returned. This return value is a huge difference between <em>open()<\/em> and <em>fopen()<\/em>.<\/p>\n<p>File descriptor values range from zero on up, with file descriptors 0, 1, and 2 all preset (and reserved) by the operating system to the following standard I\/O devices: standard input (<em>stdin<\/em>), standard output (<em>stdout<\/em>), and standard error (<em>stderr<\/em>), respectively. These constants are also defined in the <code>unistd.h<\/code> header file as: <code>STDIN_FILENO<\/code>, <code>STDOUT_FILENO<\/code>, and <code>STDERR_FILENO<\/code>.<\/p>\n<p>Just as the companion to <em>fopen()<\/em> is <em>open()<\/em>, the companion to <em>fclose()<\/em> is <em>close()<\/em>. This function is defined in the <code>unistd.h<\/code> header file (not <code>fcntl.h<\/code>), and it requires a single argument, the file descriptor integer returned by the <em>open()<\/em> function.<\/p>\n<p>The following code opens the file <code>gettysburg.txt<\/code> as did the first example, but uses the <em>open()<\/em> function. The file is opened and closed; no data is read.<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;fcntl.h&gt;\r\n#include &lt;unistd.h&gt;\r\n\r\nint main()\r\n{\r\n    const char filename[] = \"gettysburg.txt\";\r\n    int fdes;\r\n\r\n    fdes = open(filename,O_RDONLY);\r\n    if( fdes==-1 )\r\n    {\r\n        fprintf(stderr,\"Unable to open %s\\n\",filename);\r\n        return(1);\r\n    }\r\n\r\n    printf(\"'%s' opened for low-level, unformatted reading\\n\",filename);\r\n\r\n    close(fdes);\r\n\r\n    return(0);\r\n}<\/pre>\n<p>At Line 10, the <em>open()<\/em> function opens the file <code>gettysberg.txt<\/code> (referenced by variable <code>filename<\/code>) in read-only mode. The file descriptor returned is kept in the <code>fdes<\/code> variable, which is tested at Line 11.<\/p>\n<p>Line 19 closes the opened file, using the <em>close()<\/em> function with file descriptor variable <code>fdes<\/code>.<\/p>\n<p>Here&#8217;s a sample run:<\/p>\n<p><code>'gettysburg.txt' opened for low-level, unformatted reading<\/code><\/p>\n<p>In <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=4046\">next week&#8217;s Lesson<\/a>, I explore reading text from a file opened by using the <em>open()<\/em> function, and sending the text to standard output.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The common C library function to open a file is <em>fopen()<\/em>, but the <em>open()<\/em> function also exists. What&#8217;s the difference? <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=4036\">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-4036","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\/4036","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=4036"}],"version-history":[{"count":6,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4036\/revisions"}],"predecessor-version":[{"id":4146,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4036\/revisions\/4146"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4036"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4036"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4036"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}