C C

Reading a Text File in C: Totalling a Bakery's Daily Sales with fopen, fgets and sscanf

Dima Ноя 17, 2026

Introduction

Sooner or later every program needs data that lives in a file: a log, an export, a list of prices. In C, reading a file takes only a handful of functions, and a working version fits on one screen. What makes file code hard is everything that can go wrong around those functions: the file is not there, a line is damaged, the output file cannot be created. Code that ignores those cases does not just fail, it can crash or, worse, produce a total that looks right and is not.

In this tutorial we will write a program that reads a bakery till's end-of-day sales file and writes a sales report. We will start with the shortest version that reads a file and see it crash. Then we will check that the file opened, turn each line into numbers, deal with a damaged line without inventing sales, write the report to a file, and finally let the user choose which day's file to read.

I will assume you are working in the C/C++ sandbox on Bytestark, in /home/coder/learning, and that you know how to compile a program with gcc and print with printf. If you have read a number with scanf, sscanf will look familiar.


Background

C reaches files through a type called FILE, defined in stdio.h. You never create a FILE yourself. You ask fopen to open a file, and it gives you back a pointer to a FILE, written FILE *. A pointer is a value that holds the address of something in memory; here it is your handle on the open file, and you pass it to every function that reads from or writes to that file.

fopen takes two strings: the file's name and a mode. "r" opens an existing file for reading. "w" opens a file for writing, creating it if needed and emptying it if it already exists. "a" opens it for appending, adding to the end. When fopen cannot open the file, it returns NULL, a special pointer value that means "points at nothing".

Once a file is open, you read it with the same tools you use for the keyboard. fgets(buffer, size, file) reads one line into a character array, and returns NULL when there are no more lines. fprintf(file, ...) works like printf, but writes to the file. When you are done, fclose(file) closes it, which makes sure everything you wrote actually reaches the disk and gives the handle back to the operating system.

Three file handles are always open when a program starts: stdin (keyboard input), stdout (normal output, the terminal) and stderr (error messages, also the terminal by default). printf(...) is exactly fprintf(stdout, ...).


Practical Scenario

A neighbourhood bakery's till exports a small text file every evening called sales.txt. Each line is one product: its name, how many were sold, and the unit price in cents. The owner uses the day's total to reconcile the cash drawer and to order flour for the next day, so the total has to be exactly right, to the cent.

The till is old, and the file is not always perfect. On days when the till crashed there is no file at all. On busy days staff sometimes correct a line by hand and type a word where a number should be. The program that totals the file must notice both situations and say so clearly, because an owner looking at a total has no way to tell that a line was silently skipped or, worse, counted twice.

The owner also wants a report file they can print and keep, and wants to be able to total any day's file, not just tonight's.


The Problem

Here is the shortest program that reads a text file and prints every line. Create the file for the program, but do not create sales.txt yet: tonight the till crashed and there is no export.

touch sales.c


Put this in sales.c:

#include <stdio.h>

int main(void) {
    FILE *file = fopen("sales.txt", "r");
    char line[100];

    while (fgets(line, sizeof line, file) != NULL) {
        printf("%s", line);
    }

    fclose(file);
    return 0;
}


Build it and run it:

gcc -Wall -Wextra -o sales sales.c && ./sales


Segmentation fault


The program crashed. A segmentation fault is the operating system stopping a program that tried to use memory it does not own. Check the exit status:

echo $?


139


139 is how the shell reports "killed by a segmentation fault" (128 plus the signal number 11). The program never reached its own return 0;.

Let's walk through why. FILE *file = fopen("sales.txt", "r"); tries to open the file for reading. The file does not exist, so fopen returns NULL, and file holds NULL. Nothing checks that. The loop then calls fgets(line, sizeof line, file), which tries to read from the FILE that file points to. It points nowhere, so fgets reads from an invalid address, and the program is killed.

The compiler did not warn about any of this, because it cannot know whether a file will exist when the program runs. Checking is our job. And the crash is the lucky outcome here: the till operator at least knows something went wrong. The next sections deal with failures that do not announce themselves.


Checking That the File Opened

Every fopen must be followed by a check for NULL, and the program must stop or recover before it touches the file. Replace the whole of sales.c with:

#include <stdio.h>

int main(void) {
    FILE *file = fopen("sales.txt", "r");
    if (file == NULL) {
        perror("sales.txt");
        return 1;
    }

    char line[100];
    while (fgets(line, sizeof line, file) != NULL) {
        printf("%s", line);
    }

    fclose(file);
    return 0;
}


Build and run it, still without a sales.txt, and print the exit status:

gcc -Wall -Wextra -o sales sales.c && ./sales; echo $?


sales.txt: No such file or directory
1


Instead of a crash we get a clear message and an exit status of 1, which tells any script that runs this program that it failed.

if (file == NULL) is the check. When it is true, nothing after it may use file, so the block ends with return 1;, leaving main immediately.

perror("sales.txt") prints an error message to stderr. It writes the text you give it, a colon and a space, and then a description of the last error the system reported. When fopen fails, it records the reason in a variable called errno, and perror translates that number into words. That is where No such file or directory comes from: we never wrote that text. If the file existed but we were not allowed to read it, the same line would print sales.txt: Permission denied. Passing the file name as the prefix makes the message say which file the problem is about, which matters as soon as a program opens more than one.

Now create the till's export:

touch sales.txt


Put this in sales.txt:

croissant 42 180
sourdough 15 520
baguette 31 250
cinnamon-roll 18 310
rye 9 480


Run the program again:

./sales


croissant 42 180
sourdough 15 520
baguette 31 250
cinnamon-roll 18 310
rye 9 480


The file is printed back line by line. fgets reads one line per call, including its newline character, into line, and returns NULL after the last one, which ends the loop. printf("%s", line) prints the line as it is. We do not add a \n because the line already has one. Finally fclose(file) closes the file.

Try it: Run chmod 000 sales.txt, which removes every permission from the file, and then ./sales. Predict the message before you look. You will see sales.txt: Permission denied, from the same perror line, because fopen failed for a different reason and recorded a different errno. Restore the file with chmod 644 sales.txt.


Turning Each Line Into Numbers

Printing the file is not a report. We need to split each line into its three parts, multiply quantity by price, and add everything up. sscanf does the splitting: it works like scanf, but reads from a string we give it, here the line fgets just read.

We keep money in cents, as whole numbers. A double cannot represent most decimal amounts exactly, for example 0.10 is stored as something very slightly different, and those tiny errors can add up to a cent over a long list. Integers do not have this problem: 7560 cents is exactly 7560 cents.

Replace the whole of sales.c with:

#include <stdio.h>

int main(void) {
    FILE *file = fopen("sales.txt", "r");
    if (file == NULL) {
        perror("sales.txt");
        return 1;
    }

    char line[100];
    char item[32];
    int quantity = 0;
    int price_cents = 0;
    int total_cents = 0;

    while (fgets(line, sizeof line, file) != NULL) {
        sscanf(line, "%31s %d %d", item, &quantity, &price_cents);
        int line_cents = quantity * price_cents;
        printf("%-14s %3d x %2d.%02d = %3d.%02d EUR\n",
               item, quantity, price_cents / 100, price_cents % 100,
               line_cents / 100, line_cents % 100);
        total_cents += line_cents;
    }

    fclose(file);
    printf("Total: %d.%02d EUR\n", total_cents / 100, total_cents % 100);
    return 0;
}


gcc -Wall -Wextra -o sales sales.c && ./sales


croissant       42 x  1.80 =  75.60 EUR
sourdough       15 x  5.20 =  78.00 EUR
baguette        31 x  2.50 =  77.50 EUR
cinnamon-roll   18 x  3.10 =  55.80 EUR
rye              9 x  4.80 =  43.20 EUR
Total: 330.10 EUR


Each line is now priced, and the total is 330.10 EUR. Let's check one line by hand: 42 croissants at 180 cents is 7560 cents, which is 75.60 EUR. Here is how the new code gets there.

sscanf(line, "%31s %d %d", item, &quantity, &price_cents) reads three things from line:

  • %31s reads a word: it skips leading spaces, then copies characters into item until it reaches a space. The 31 is a maximum. item has room for 32 characters, and a C string always needs one extra byte for the zero that marks its end, so we allow at most 31 letters. Without the limit, a very long word in the file would be written past the end of item, overwriting whatever is next in memory.
  • item has no & in front of it, unlike the two integers. An array's name, used like this, already stands for the address of its first element, which is what sscanf needs. quantity and price_cents are plain variables, so we pass their addresses with &.
  • Each %d skips spaces and reads an integer.

int line_cents = quantity * price_cents; is the line's value in cents, and total_cents += line_cents; adds it to the running total.

The money is printed by splitting cents into euros and the remainder. line_cents / 100 is integer division, so 7560 / 100 is 75. line_cents % 100 is the remainder, 60. The format %d.%02d prints them with a dot between and pads the cents to two digits with a zero, so that 5 cents prints as .05 and not .5.

The other widths are only there to line the columns up. %-14s prints the word in a field 14 characters wide, and the - means left-aligned, padded on the right. %3d and %2d pad numbers on the left to 3 and 2 characters.

Try it: In the per-product printf, change the last %02d, the one that prints line_cents % 100, to %d. Then change the croissant price in sales.txt from 180 to 181 and rebuild. Predict the croissant line before you run. It shows = 76.2 EUR instead of 76.02, because 42 × 181 = 7602 cents leaves a remainder of 2, and only %02d pads it to two digits. The sourdough line changes too, to 78.0 EUR, because its remainder is 0. The total line, which still uses %02d, prints Total: 330.52 EUR correctly. Put the %02d and the price 180 back.


A Damaged Line Must Not Invent Sales

Today a staff member added a line by hand, and typed the quantity as a word. Edit sales.txt so that it reads:

croissant 42 180
sourdough 15 520
pain-au-chocolat twelve 290
baguette 31 250
cinnamon-roll 18 310
rye 9 480


Run the program without changing it:

./sales


croissant       42 x  1.80 =  75.60 EUR
sourdough       15 x  5.20 =  78.00 EUR
pain-au-chocolat  15 x  5.20 =  78.00 EUR
baguette        31 x  2.50 =  77.50 EUR
cinnamon-roll   18 x  3.10 =  55.80 EUR
rye              9 x  4.80 =  43.20 EUR
Total: 408.10 EUR


Look at the third line, and then at the total. The program invented a sale: 15 pain au chocolat at 5.20 EUR, exactly the numbers of the sourdough line above it, and added 78.00 EUR to the total. This is worse than a crash. The owner would count the cash drawer, find 78 EUR missing, and suspect the staff.

Here is what happened. For the line pain-au-chocolat twelve 290, %31s read pain-au-chocolat into item. Then %d met twelve, which is not a number, and sscanf stopped. It did not change quantity or price_cents, so they still held 15 and 520 from the sourdough line. The program never checked whether sscanf succeeded, so it carried on with those stale values.

sscanf, like scanf, returns how many values it filled. A good line fills all three, so anything other than 3 means the line cannot be trusted. Replace the while loop, and add a line counter just before it, so that this part of sales.c reads:

    int line_number = 0;

    while (fgets(line, sizeof line, file) != NULL) {
        line_number++;
        if (sscanf(line, "%31s %d %d", item, &quantity, &price_cents) != 3) {
            fprintf(stderr, "sales.txt:%d: skipped, expected: item quantity price\n", line_number);
            continue;
        }
        int line_cents = quantity * price_cents;
        printf("%-14s %3d x %2d.%02d = %3d.%02d EUR\n",
               item, quantity, price_cents / 100, price_cents % 100,
               line_cents / 100, line_cents % 100);
        total_cents += line_cents;
    }


gcc -Wall -Wextra -o sales sales.c && ./sales


croissant       42 x  1.80 =  75.60 EUR
sourdough       15 x  5.20 =  78.00 EUR
sales.txt:3: skipped, expected: item quantity price
baguette        31 x  2.50 =  77.50 EUR
cinnamon-roll   18 x  3.10 =  55.80 EUR
rye              9 x  4.80 =  43.20 EUR
Total: 330.10 EUR


The damaged line is reported with its line number and left out, and the total is back to 330.10 EUR. Nothing was invented. The owner now knows exactly which line to fix by hand, and that the total does not include it.

  • int line_number = 0; and line_number++; count lines as they are read, so the message can say where the problem is. Line numbers start at 1 because people count lines from 1, even though C counts array elements from 0.
  • if (sscanf(...) != 3) accepts a line only if all three values were filled. One check covers every kind of damage: a word instead of a number, a missing price, an empty line.
  • fprintf(stderr, ...) writes the warning to the error stream instead of standard output. On the terminal both look the same, but they are separate streams, and that becomes useful as soon as output is saved to a file.
  • The message format, sales.txt:3: ..., follows the same file:line: convention as compiler messages, which many editors and tools understand.
  • continue; skips the rest of the loop body for this line, so the stale values are never multiplied or added.

Try it: Run ./sales 2>/dev/null. The 2> part redirects stream number 2, which is stderr, to /dev/null, a special file that throws away everything written to it. Predict what disappears. Only the sales.txt:3: skipped line vanishes; the report and total are untouched, because they go to stdout. That separation is the reason warnings belong on stderr.


Writing the Report to a File

The owner wants a report they can keep and print. Before we change the program, save today's damaged file for later and repair sales.txt:

cp sales.txt saturday.txt


Then delete the pain-au-chocolat line from sales.txt, so it holds the original five lines again.

Writing a file is the mirror image of reading one: open it with mode "w", check for NULL, write with fprintf, close it. Replace the whole of sales.c with:

#include <stdio.h>

int main(void) {
    FILE *file = fopen("sales.txt", "r");
    if (file == NULL) {
        perror("sales.txt");
        return 1;
    }

    FILE *report = fopen("report.txt", "w");
    if (report == NULL) {
        perror("report.txt");
        fclose(file);
        return 1;
    }

    char line[100];
    char item[32];
    int quantity = 0;
    int price_cents = 0;
    int total_cents = 0;
    int line_number = 0;

    while (fgets(line, sizeof line, file) != NULL) {
        line_number++;
        if (sscanf(line, "%31s %d %d", item, &quantity, &price_cents) != 3) {
            fprintf(stderr, "sales.txt:%d: skipped, expected: item quantity price\n", line_number);
            continue;
        }
        int line_cents = quantity * price_cents;
        fprintf(report, "%-14s %3d x %2d.%02d = %3d.%02d EUR\n",
                item, quantity, price_cents / 100, price_cents % 100,
                line_cents / 100, line_cents % 100);
        total_cents += line_cents;
    }

    fprintf(report, "Total: %d.%02d EUR\n", total_cents / 100, total_cents % 100);
    fclose(report);
    fclose(file);

    printf("Report written to report.txt (%d lines read)\n", line_number);
    return 0;
}


Build and run it, then look at the new file with cat, which prints a file to the terminal:

gcc -Wall -Wextra -o sales sales.c && ./sales && cat report.txt


Report written to report.txt (5 lines read)
croissant       42 x  1.80 =  75.60 EUR
sourdough       15 x  5.20 =  78.00 EUR
baguette        31 x  2.50 =  77.50 EUR
cinnamon-roll   18 x  3.10 =  55.80 EUR
rye              9 x  4.80 =  43.20 EUR
Total: 330.10 EUR


The program itself printed only the first line. Everything after it was printed by cat from report.txt. The program is 43 lines long now, so let's go through it in its three parts.

The opening part opens both files:

    FILE *report = fopen("report.txt", "w");
    if (report == NULL) {
        perror("report.txt");
        fclose(file);
        return 1;
    }


Mode "w" creates report.txt if it does not exist and empties it if it does, so each run produces a fresh report rather than adding to yesterday's. It can still fail, for example if the folder is read-only, so it gets the same NULL check as the input file. Notice the fclose(file); before returning: at this point the sales file is already open, and the program should close what it opened before giving up.

The loop is the same as before, with one change: the line that formats each product now starts with fprintf(report, ... instead of printf(.... The arguments after the file handle are exactly the ones printf had, which is the point: printf is fprintf with stdout filled in. The warning still goes to stderr, because it is meant for the person running the program right now, not for the printed report.

The closing part writes the total into the report, closes both files, and tells the user what happened:

    fprintf(report, "Total: %d.%02d EUR\n", total_cents / 100, total_cents % 100);
    fclose(report);
    fclose(file);

    printf("Report written to report.txt (%d lines read)\n", line_number);


fclose(report) matters more for writing than for reading. fprintf does not send each line to the disk immediately: it collects output in a buffer in memory and writes it out in larger pieces, because writing to a disk is slow. fclose writes whatever is still in the buffer and then closes the file. When main returns normally, C closes open files for you, but a program that crashes or is killed before that point loses whatever was still in the buffer. Closing explicitly, as soon as you are done, is the habit that prevents half-written reports.

Try it: Change the report's mode from "w" to "a", rebuild, and run ./sales && ./sales && cat report.txt. Predict how many Total: lines the report holds. It holds three: one from the earlier "w" run, then one more for each of the two "a" runs, because append mode adds to the end instead of starting from an empty file. Change it back to "w" and run once more to get a clean report.


Choosing the File From the Command Line

The program can only total sales.txt. To total Saturday's file, the owner would have to edit the source and rebuild. Instead, the file name should be given when the program is run, as in ./sales saturday.txt. Those extra words are command-line arguments, and C passes them to main if main asks for them.

Make two changes to sales.c. First, replace the beginning of main, up to and including the first perror block, with:

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "usage: %s SALES_FILE\n", argv[0]);
        return 2;
    }

    const char *path = argv[1];
    FILE *file = fopen(path, "r");
    if (file == NULL) {
        perror(path);
        return 1;
    }


Second, change the warning inside the loop so it names the file that was actually read:

            fprintf(stderr, "%s:%d: skipped, expected: item quantity price\n", path, line_number);


Leave the rest as it is. Build it and try three ways of running it: with no file name, with a file that does not exist, and with sales.txt:

gcc -Wall -Wextra -o sales sales.c && ./sales; echo $?


usage: ./sales SALES_FILE
2


./sales monday.txt; echo $?


monday.txt: No such file or directory
1


./sales sales.txt; echo $?


Report written to report.txt (5 lines read)
0


Each run ends with a different exit status, and each one means something: 2 for "you called the program wrong", 1 for "the file could not be read", 0 for success. Here is what changed.

int main(int argc, char *argv[]) is the other allowed form of main. argc, the argument count, is how many words were on the command line, including the program's own name. argv, the argument vector, is an array of those words as strings: argv[0] is the program name, argv[1] the first argument, and so on. For ./sales sales.txt, argc is 2, argv[0] is "./sales" and argv[1] is "sales.txt".

if (argc != 2) checks that exactly one file name was given. If not, we print a usage message, the conventional one-line reminder of how to call the program, built from argv[0] so it shows the name the user actually typed.

const char *path = argv[1]; gives the file name a readable name of its own. char * is the type C uses for a string, a pointer to its first character, and const says we will not modify it. From here on, path replaces every place where "sales.txt" was written: in fopen, in perror, and in the warning.

Now total Saturday's damaged file, the one we saved earlier:

./sales saturday.txt


saturday.txt:3: skipped, expected: item quantity price
Report written to report.txt (6 lines read)


The warning now names saturday.txt, so the owner knows which file to fix. Six lines were read and one was skipped, and report.txt holds a report with the same five products and the same 330.10 EUR total as before.

Try it: Run ./sales report.txt, asking the program to read its own report. Before you run it, think about the order of the two fopen calls. The program prints Report written to report.txt (0 lines read), and cat report.txt shows only Total: 0.00 EUR. Opening report.txt with "w" emptied it before the loop read a single line, so the input file was destroyed by the output file. A real tool would refuse when the input and output names are the same. Run ./sales sales.txt to restore the report.


Summary

We built a sales totaller for a bakery's till export that refuses to run on a missing file, refuses to count a damaged line, writes a printable report, and reads whichever day's file it is given. We kept the file format deliberately simple, one product per line separated by spaces. Real exports often use comma-separated values with quoted fields, which need a proper parser and are a topic of their own.

  • fopen returns NULL when it cannot open a file. Check it every time, before the handle is used, because reading from NULL crashes the program.
  • perror(name) prints name: followed by the system's reason for the last failure, such as No such file or directory or Permission denied.
  • Read a file line by line with while (fgets(line, sizeof line, file) != NULL); fgets keeps the newline and returns NULL after the last line.
  • Check that sscanf filled every value you asked for. On a failed conversion it leaves the variables unchanged, so they still hold the previous line's values.
  • Limit every %s with a width one less than the buffer size, such as %31s for char item[32], so a long word cannot overflow the array.
  • Keep money in integer cents and print it with / 100, % 100 and %02d.
  • Send warnings to stderr with fprintf(stderr, ...) and results to stdout or a file, so that redirecting one does not hide or pollute the other.
  • Mode "w" empties the file it opens and "a" appends to it. fclose flushes buffered output to the disk, so close output files as soon as you are done with them.
  • main(int argc, char *argv[]) receives the command-line words. Check argc before using argv, and return different exit statuses for different failures.

Чтобы получить доступ к облачной лаборатории, необходимо войти в систему.

Войти