{"id":3321,"date":"2018-10-13T00:01:33","date_gmt":"2018-10-13T07:01:33","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=3321"},"modified":"2018-10-20T10:21:50","modified_gmt":"2018-10-20T17:21:50","slug":"file-writing-and-reading","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=3321","title":{"rendered":"File Writing and Reading"},"content":{"rendered":"<p>Sending text to standard output is something you learn with your first C program. The common functions are <em>putchar()<\/em>, <em>puts()<\/em>, <em>printf()<\/em>, and so on. When you explore file access, you&#8217;ll find familiarity in those functions because they&#8217;re quite similar to the standard I\/O functions.<br \/>\n<!--more--><br \/>\nBefore you can output text to a file, the file must be opened in writing or appending mode:<\/p>\n<p><code>f = fopen(filename,\"w\");<\/code><\/p>\n<p>The above statement opens a file. The name is represented by variable <code>filename<\/code> and the mode is <code>\"w\"<\/code> for write. If the file exists, it&#8217;s overwritten.<\/p>\n<p>Once open, you can use file-oriented versions of the standard output functions. For example, <em>fprintf()<\/em>, which works just like the <em>printf()<\/em> function, but adds the file&#8217;s handle as the function&#8217;s first argument:<\/p>\n<p><code>fprintf(f,\"Goodbye, cruel world!\\n\");<\/code><\/p>\n<p>The above statement writes text to the open file represented by <code>FILE<\/code> variable <code>f<\/code>. And that&#8217;s it! <\/p>\n<p>Secretly (shhh!), the text is stored in a file-writing buffer, which is part of the operating system. For efficiency&#8217;s sake, data is written to files in goodly-sized chunks. Depending on the file system, the chunk could be 2K in size. The output is written when the buffer is full, manually flushed by using a special function, or when the file is closed.<\/p>\n<p>The following code opens a file named <code>output.txt<\/code>, writes a string to the file, then closes the file:<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\nint main()\r\n{\r\n    const char filename[] = \"output.txt\";\r\n\r\n    FILE *f;\r\n\r\n    <span class=\"comments\">\/* open\/create the file *\/<\/span>\r\n    printf(\"Creating '%s'\\n\",filename);\r\n    f = fopen(filename,\"w\");\r\n    if( f == NULL )\r\n    {\r\n        fprintf(stderr,\"Unable to create file '%s'\\n\",filename);\r\n        return(1);\r\n    }\r\n\r\n    <span class=\"comments\">\/* write some text *\/<\/span>\r\n    fprintf(f,\"This is a text file\\n\");\r\n    puts(\"Text written\");\r\n\r\n    <span class=\"comments\">\/* close the file *\/<\/span>\r\n    fclose(f);\r\n    puts(\"Done\");\r\n\r\n    return(0);\r\n}<\/pre>\n<p>This code is similar to the file opening and closing example from <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=3314\">last week&#8217;s Lesson<\/a>.<\/p>\n<p><code>filename<\/code> is defined as a constant character array at Line 5. It&#8217;s opened at Line 11. At Line 19, the <em>fprintf()<\/em> statement sends a line of text to the file. And the file is closed with <em>fclose()<\/em> at Line 23. All the while, various other statements output text to standard output, updating you on the progress. That way you see feedback as the program runs:<\/p>\n<pre><code>$ .\/a.out\r\nCreating 'output.txt'\r\nText written\r\nDone\r\n$ cat output.txt\r\nThis is a text file\r\n$ <\/code><\/pre>\n<p>In the terminal output (above), I used the <em>cat<\/em> command to view the file&#8217;s contents. You can also fetch the file&#8217;s contents by opening it in read mode and using the file-based version of standard input functions to extract the file&#8217;s text. The following code does that:<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\nint main()\r\n{\r\n    const char filename[] = \"output.txt\";\r\n    char buffer[64];\r\n    FILE *f;\r\n\r\n    <span class=\"comments\">\/* open file for reading *\/<\/span>\r\n    printf(\"Reading from '%s'\\n\",filename);\r\n    f = fopen(filename,\"r\");\r\n    if( f == NULL )\r\n    {\r\n        fprintf(stderr,\"Unable to open file '%s'\\n\",filename);\r\n        return(1);\r\n    }\r\n\r\n    <span class=\"comments\">\/* read text from the file *\/<\/span>\r\n    fgets(buffer,64,f);\r\n    printf(\"File contents: %s\\n\",buffer);\r\n\r\n    <span class=\"comments\">\/* close the file *\/<\/span>\r\n    fclose(f);\r\n    puts(\"Done\");\r\n\r\n    return(0);\r\n}<\/pre>\n<p>As with the earlier code, the <code>filename<\/code> constant holds the file&#8217;s name &mdash; and it&#8217;s assumed that this file was created earlier and is a text file. A character buffer is also created at Line 6, which holds text read from the file.<\/p>\n<p>At Line 11, the <em>fopen()<\/em> function opens the file in &#8220;r&#8221;, read mode. The <em>fgets()<\/em> function at Line 19 reads text from file <code>f<\/code> and stores it in buffer. The number of characters to read, 64, is the same size as the buffer; the <em>fgets()<\/em> function won&#8217;t overflow the buffer. The <em>fclose()<\/em> statement at Line 23 closes the file. And various standard output functions update the user on the program&#8217;s progress.<\/p>\n<p>Here&#8217;s a sample run:<\/p>\n<pre><code>Reading from 'output.txt'\r\nFile contents: This is a text file\r\n\r\nDone<\/code><\/pre>\n<p>In <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=3330\">next week&#8217;s Lesson<\/a>, I cover writing and reading larger chunks of text.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Don&#8217;t worry about losing your sanity because many of the standard I\/O functions have file-oriented counterparts. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=3321\">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-3321","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\/3321","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=3321"}],"version-history":[{"count":5,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/3321\/revisions"}],"predecessor-version":[{"id":3342,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/3321\/revisions\/3342"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3321"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3321"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3321"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}