Skip to main content
Logo image

Section 16.6 Back to File I/O

Here is our overarching goal:
Write a barcode (UPC) checksum program: Read 12 digits of a barcode from a file. (The first digit indicates the type of product being identified, the next five identify the manufacturer, the next five identify the product, and the last digit (12th digit) is a check digit).
Next, compute the proper check digit: Sum the first, third, fifth, seventh, ninth and eleventh digits, and multiply the result by 3. Next, sum the second, fourth, sixth, eighth, and tenth digits. Add this new sum to the first result. Finally, fin d the smallest number that needs to be added to this total to make it equal a multiple of 10. This number is the check digit.
Print the computed check digit as well as the one read from file.
Here is an example:
Sample Barcode

Activity 16.6.

Your first task: Check by hand if the calculated check digit equals the check digit in the image.
Do the calculations agree with the barcode?
  • Yes!
  • No...
Write a C program that reads 12 integers from the file sampleBarcode.txt. Your program should perform the following tasks:
  • print the barcode to the screen
  • computes the check digit
  • compares the computed check digit with the actual check digit
  • print a message to the screen indicating whether the barcode was correctly read.
The code window below contains a file "sampleBarcode.txt". If you’d rather work on the server then you need to create your own such file and fill it with 12 integers.

admin.....open in new window

When you are done, please paste your code into the code submission box below:

Subsection 16.6.1 Optional: Make it fancier!

Activity 16.7.

  1. In your previous program, build in a check as to whether the file from which you are reading exists.
  2. Write a C program that asks the user to enter a 12-digit barcode and that saves this barcode in a file (you may choose the filename). Note that you’ll have to write this program in your own editor and compile on the server since we cannot write to files from code windows.