Skip to content
Laviyx Learn

Try

PPS Lab · Experiment 31

Create and update a binary file of integers

CFilesJNTUH R22 · CS108ES

Aim

To write a C program that creates a binary file and stores 10 integers in it, where the file name and the 10 values are given on the command line. The program then reads an index and a new value from the user, changes the value at that index in the file using fseek, and finally reads all 10 values back from the file and prints them.

Algorithm

  1. Check that the command line has a file name and exactly 10 values. If not, print how to use the program and stop.
  2. Convert the 10 value strings to integers with atoi.
  3. Open the file in "wb" mode, write the 10 integers with fwrite, and close it.
  4. Read the index (0 to 9) and the new value from the keyboard. If the index is outside 0 to 9, print an error and stop.
  5. Open the file in "rb+" mode. Move to byte position index × sizeof(int) with fseek and write the new value with fwrite.
  6. Move back to the start of the file with rewind, read all 10 integers with fread, and print them.
  7. Close the file.

Program

C
#include <stdio.h>
#include <stdlib.h>

#define N 10

int main(int argc, char *argv[]) {
    int values[N], index, new_value;

    if (argc != N + 2) {
        printf("Usage: %s <file name> <10 integers>\n", argv[0]);
        return 1;
    }
    for (int i = 0; i < N; i++) {
        values[i] = atoi(argv[i + 2]);
    }

    /* Step 1: create the binary file and store the 10 integers */
    FILE *fp = fopen(argv[1], "wb");
    if (fp == NULL) {
        printf("Cannot create file %s\n", argv[1]);
        return 1;
    }
    fwrite(values, sizeof(int), N, fp);
    fclose(fp);
    printf("%d integers written to %s\n", N, argv[1]);

    /* Step 2: read the index and the new value */
    printf("Enter the index to change (0 to %d): ", N - 1);
    if (scanf("%d", &index) != 1 || index < 0 || index >= N) {
        printf("Invalid index\n");
        return 1;
    }
    printf("Enter the new value: ");
    if (scanf("%d", &new_value) != 1) {
        printf("Invalid value\n");
        return 1;
    }

    /* Step 3: change the value at that index inside the file */
    fp = fopen(argv[1], "rb+");
    if (fp == NULL) {
        printf("Cannot open file %s\n", argv[1]);
        return 1;
    }
    fseek(fp, index * (long) sizeof(int), SEEK_SET);
    fwrite(&new_value, sizeof(int), 1, fp);

    /* Step 4: read all 10 values back from the file */
    rewind(fp);
    int count = (int) fread(values, sizeof(int), N, fp);
    fclose(fp);

    printf("Values in the file after the update:\n");
    for (int i = 0; i < count; i++) {
        printf("%d ", values[i]);
    }
    printf("\n");
    return 0;
}

Output

Change the value at index 3

Output 1
$ ./a.out numbers.dat 10 20 30 40 50 60 70 80 90 100
10 integers written to numbers.dat
Enter the index to change (0 to 9): 3
Enter the new value: 444
Values in the file after the update:
10 20 30 444 50 60 70 80 90 100 

Index outside the file

Output 2
$ ./a.out numbers.dat 5 10 15 20 25 30 35 40 45 50
10 integers written to numbers.dat
Enter the index to change (0 to 9): 12
Invalid index

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

The index starts at 0, like an array index, so index 3 is the fourth number.

In a binary file each int is stored as its raw bytes (sizeof(int), usually 4), not as text. So the value at index i starts at byte i × sizeof(int), and fseek can jump straight to it without reading the numbers before it.

When a file is opened for update ("rb+"), C requires an fseek, rewind or fflush between a write and a following read. Here rewind does that job and also moves back to the start.

The binary file is not readable in a text editor; the program itself reads the values back to show them.

Common mistakes

  • Opening the file with "wb" the second time. That erases all 10 numbers. Use "rb+" to read and change an existing file without emptying it.

  • Writing fseek(fp, index, SEEK_SET). The offset is in bytes, not in integers, so it must be index * sizeof(int).

  • Reading right after writing without calling fseek or rewind in between. On an update stream this is not allowed and can give wrong data.

  • Using argv[1] to argv[10] for the values. argv[1] is the file name, so the 10 values are argv[2] to argv[11], and argc must be 12.

Viva questions

Try to answer each one aloud before you open it.

  • What is the difference between a text file and a binary file?

    A text file stores data as readable characters, so the number 444 is stored as the characters '4', '4', '4'. A binary file stores the bytes of the value as they are in memory, so an int always takes sizeof(int) bytes.

  • What do the arguments of fseek mean?

    fseek(fp, offset, origin) moves the file position to offset bytes from origin. The origin is SEEK_SET (start of file), SEEK_CUR (current position) or SEEK_END (end of file).

  • What do fwrite and fread return?

    The number of items (not bytes) actually written or read. If it is less than the number asked for, an error occurred or the end of the file was reached.

  • What does atoi do?

    atoi (ASCII to integer) converts a string of digits such as "40" into the int value 40. It is declared in stdlib.h.

  • What is the difference between the modes "rb+" and "wb+"?

    Both allow reading and writing. "rb+" opens an existing file and keeps its contents; "wb+" creates the file or empties it if it exists.

  • What does rewind(fp) do?

    It moves the file position back to the beginning of the file, the same as fseek(fp, 0, SEEK_SET), and also clears the error indicator.

Learn the concepts

All Programming for Problem Solving Lab experiments →