UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

9.8.8.  Read an unknown number of integers from a file

Resources

  • For this activity you may start with the source code from fread_fixed_integers.c, which read integers from a file. Copy that code in the folder fread_variable in your shared folder.

  • Section 3 from Reading and writing with files

Work Plan

Files in Linux are simply a sequence of bytes. If a file stores data of arbitrary size, then we should know the amount of data to read to give it as a parameter to the function fread. There are several ways to solve this problem, and one of them consists of include as first element an integer with the size of data size. This way, the first data read is an integer indicating how much data is stored in the next positions. The following figure shows this technique for a file with 5 integers.

SIZE|INTEGER_0|INTEGER_1|INTEGER_2

Modify the program fread_fixed_integers.c, and call it fread_variable_integers.c. It should read the integers from a file with that structure (a binary file with numbers stored in consecutive positions, being the first number the number of elements):

Your program should read the size and allocate memory with the malloc function. Do not forget of using the free function to free the allocated memory before the end of your program.

Check the program with these data files: fich_10_enteros and fich_enteros that you can find in the fread_variable sub-folder in your shared folder.

Upload the program to the folder fread_variable in your workspace in Subversion.