<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Srihari on Medium]]></title>
        <description><![CDATA[Stories by Srihari on Medium]]></description>
        <link>https://medium.com/@srihari1650?source=rss-e5accf82f645------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kR7BS7D7DZWjw7wM</url>
            <title>Stories by Srihari on Medium</title>
            <link>https://medium.com/@srihari1650?source=rss-e5accf82f645------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 02:33:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srihari1650/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bytes on Disk: A Deep Dive into File Handling in C]]></title>
            <link>https://medium.com/@srihari1650/bytes-on-disk-a-deep-dive-into-file-handling-in-c-acb99e26194c?source=rss-e5accf82f645------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb99e26194c</guid>
            <dc:creator><![CDATA[Srihari]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 11:36:31 GMT</pubDate>
            <atom:updated>2026-09-22T11:36:31.503Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>How Programs Store and Retrieve Data</em></strong></p><p>Every C program forgets everything the moment it closes — unless you teach it to write things down. This is how it does that.</p><ol><li><strong>The problem nobody mentions on day one</strong></li></ol><p>Think about the first C program one writes. One declares a variable, stores a number into it, prints the number, and terminates the program. What happens to the number once the program terminates? It vanishes, gone for good, lost forever. This is expected, as RAM is a whiteboard; the moment the power to your process is cut, the marker is put down. Now, consider any real-world application that you can think of — a note-taking application, a game with a save system, or even a portal displaying your college results. Does it forget you as soon as you close it? No, it does not. There has to be something, somewhere, that is persisting your data, writing it to a place where it will not be erased when the program closes.</p><p>A file, and the set of tools provided by C to manipulate it, is that something.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*NGwvWmwXR8fq7kkGM_eYBw.png" /></figure><p><strong>2. The one object that represents “a notebook, currently open”</strong></p><p>Before you can write in your notebook, it has to be open on the desk in front of you. C represents that opened notebook with a single struct, FILE defined for you in. You never have to muck around with the innards of a FILE struct — you simply hold a pointer to it and pass that pointer to every function that needs to read or write.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*dfSkHUZVQFUvSwVckUuhjg.png" /></figure><p>fopen() returns NULL on failure — disk full, bad filename, permission denied, etc., and checking that the returned pointer isn’t NULL is not optional.</p><p>The second argument to fopen() determines whether you’re opening the notebook for reading, or to start a fresh page, or to add to the end of what’s already there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*kB0aZvs8gWE57JhztaGKQA.png" /></figure><p>Add a b anywhere in the mode (like “rb” or “wb”) and you’ll tell C to treat the file as being made up of raw bytes, not text — why that might be useful is explored in section 05.</p><p><strong>3. Writing: getting data out of RAM and onto disk</strong></p><p><em>Three ways to write, from “formatted like printf” to “raw and fast”.</em></p><p>Say you’re making the world’s tiniest student register. Every time you add a student, you want to save a line to a permanent record. fprintf is the way to go here — it’s printf’s cousin, except that the first argument tells it where to print to, instead of the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*gJPd921rH0aipFcKS8mO9Q.png" /></figure><p>Running this code twice will make students.txt contain two lines — that’s the “a” mode in action. Try “w”, and it’ll be emptied every time.</p><p>If you need to write one character at a time, there’s always fputc. And if you’re not printing text data at all, but some binary structure — say, a record, an image, or a chunk of a video — then fwrite will copy the raw memory content to the file on disk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*OboPV9aRtMwpHtWodZrXtg.png" /></figure><p><strong>5. Reading: bringing it back into RAM</strong></p><p>Like writing, reading can be done in various ways, but the functions are similar to the scanf family. fscanf is the analogue of scanf, returning formatted values from the file, while fgetc reads single characters and fread reads raw bytes into a struct. The one habit that trips almost everyone on their first attempt is that you have no idea how many lines you’ve read, so you just keep going until you can’t read anything else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*t-MauJNhuiFL-9FDGo7Y9A.png" /></figure><p>The value returned by fscanf is the number of values successfully read and assigned. This can be used to determine when you’ve hit the end of the file (or, more likely, when you’ve attempted to read past the end of the file), since it will stop returning the expected number of values.</p><p>If you want to check explicitly whether you’ve hit the end of the file, feof(fp) will be true if the last read operation attempted to read past the end of the file. This is most useful in loops using fgetc or fread.</p><p><strong>5.Two totally different kinds of notebook: text versus binary</strong></p><p>This is the kind of distinction that students who have studied it often mix up. Text file stores characters as numbers — what you see in the file is actually ASCII codes. Binary file stores the raw data that was in the memory. You can test in Notepad — open a text file and you can see what you wrote. Open a binary file and you will see junk because it is not text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*i-lTsf_MKg1emK280cIIpw.png" /></figure><p>A save-game system is a useful application for either type of file. The text version is much easier to edit or debug, while the binary version is much faster to read/write, and harder for someone using a text editor to muck with accidentally.</p><p><strong>6. Jumping around instead of reading start-to-finish</strong></p><p>So far, each example shows how to read a file from beginning to end, like reading a novel. However, many file formats also allow you to jump to a specific page, skipping over pages 1 through 39 to read page 40. This random-access capability is based on a simple concept: Each open file has an invisible bookmark called the file position indicator, and there are three standard functions for moving this bookmark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*IVj_4jwlyv_xry0I1MUwsw.png" /></figure><p>Only the bytes for that one record change on disk — the other 999 students are never touched. That’s the entire reason random access exists.</p><p><strong>7. Building something real: a two-file “mini diary”</strong></p><p>Putting reading, writing and appending together in one small working idea.</p><p>Here’s a genuinely useful five-minute project that uses all of the above: a command-line diary that appends a dated-by-you entry to a growing file, and can print out all entries on demand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*CyUC0PQaj1J-f16lMthdfQ.png" /></figure><p>But notice what’s really happening: main() has no idea what’s been written yesterday or last week or ten minutes ago in a prior run of the program. It doesn’t need to — diary.txt is the memory now. That this same pattern underlies how a library management system remembers all books or a banking program remembers all balances or how a game remembers where you left off is the point.</p><p><strong>8. The kinds of mistakes which are most costly (in terms of lost marks, or debugging time)</strong></p><p>Not checking the result of fopen for NULL pointers. (A missing file, or disk full condition, etc., will cause subsequent fprintf or fscanf calls to crash, with no clear explanation.)</p><p>Not calling fclose. (Data written by fprintf or fwrite may be held in a buffer and not actually written to the file until the file is closed. So a “saved” file may turn out to be empty if the program terminates abnormally.)</p><p>Using “w” instead of “a” when opening a file for appending. (“w” causes the file to be truncated, so using “w” when you mean “a” is a common way to delete an entire data file.)</p><p>Confusing the two arguments to fread and fwrite. (The second argument is the size of each item, in bytes; the first argument is the number of items, and should almost always be 1.)</p><p>Trying to read a binary file as if it were a text file, or vice versa. (The bit patterns are the same in either case, so there’s no fundamental difference between the two kinds of file; the problem is in using the wrong format codes when reading or writing.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*zqmspRRxNmSF5eCRuEloew.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb99e26194c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>