← Back to problems
UNSW COMP1521 · medium

COMP1521 2020T3 Q6 — File I/O

COMP1521 2020T3 Q6 · 9 marks · C Topic: File I/O · Source: https://cgi.cse.unsw.edu.au/~cs1521/26T1/resources/practice_exams.html

Summary: Count the total set bits in a file

We need to count the number of bits which are set in a file. A bit is said to be set if it is 1 .

Write a C program, 20t3final_q6.c , which takes a single filename as its argument.

20t3final_q6.c should read the bytes of the file, counting the number of bits that are set (1) in each byte.

20t3final_q6.c should print one line of output containing the total number of bits which were set.

You must match the output format in the example below exactly.

dcc 20t3final_q6.c -o 20t3final_q6 echo > file0 xxd file0 00000000: 0a . ./20t3final_q6 file0 file0 has 2 bits set echo hello world > file1 xxd file1 00000000: 6865 6c6c 6f20 776f 726c 640a hello world. ./20t3final_q6 file1 file1 has 47 bits set ./20t3final_q6 20t3final_q6.0.bin 20t3final_q6.0.bin has 1024 bits set ./20t3final_q6 20t3final_q6.1.bin 20t3final_q6.1.bin has 8084 bits set ./20t3final_q6 20t3final_q6.2.bin 20t3final_q6.2.bin has 9720 bits set

There is no supplied code for this question.

No error checking is required.

Your program can assume it is always given one argument: the name of a file.

The file may contain any byte.

Your program can assume the number of bits set can be stored in a int variable without overflow.

Your solution must be in C only.

You are not permitted to run external programs. You are not permitted to use system, popen, posix_spawn, fork or exec.


🤖 Write a C program. argv[1] is a filename (in the run workspace). Sum the number of 1-bits over every byte and print exactly: <filename> has <total> bits set.

Fixture files are provided in the run workspace; reference outputs verified on the sandbox.