PROGRAMMING III FilesStructures Vladimir Viies Lembit Jrimgi Margit
PROGRAMMING I=>II( Files+Structures) Vladimir Viies, Lembit Jürimägi, Margit Jan Toodre, Marina Brik vladimir. viies@gmail. com Tallinn 2017
Homework (I)-example Files and structures n n n Write an algorithm and matching code for a program with the following functional requirements: Data is read from a plain text file „F 1. txt“ and stored as a structure. The data file must contain the given attributes: p Name - string p Age - integer p Income - floating point Program will output: p To file „F 2. txt“ all of the entries whose age is below the average. p To file „F 3. txt“ all of the entries whose income is above the average.
File system
File Concept n Contiguous logical address space n Types: p Data numeric £ character £ binary £ p Program
File Structure n n None - sequence of words, bytes Simple record structure p p p n Complex Structures p p n n Lines Fixed length Variable length Formatted document Relocatable load file Can simulate last two with first method by inserting appropriate control characters Who decides: p Operating system p Program
File Attributes n n n n Name – only information kept in human-readable form Identifier – unique tag (number) identifies file within file system Type – needed for systems that support different types Location – pointer to file location on device Size – current file size Protection – controls who can do reading, writing, executing Time, date, and user identification – data for protection, security, and usage monitoring Information about files are kept in the directory structure, which is maintained on the disk
File Operations n n n n n File is an abstract data type Create Write Read Reposition within file Delete Truncate Open(Fi) – search the directory structure on disk for entry Fi, and move the content of entry to memory Close (Fi) – move the content of entry Fi in memory to directory structure on disk
Open Files n Several pieces of data are needed to manage open files: p p File pointer: pointer to last read/write location, per process that has the file open File-open count: counter of number of times a file is open – to allow removal of data from open-file table when last processes closes it Disk location of the file: cache of data access information Access rights: per-process access mode information
Access Methods n n Sequential Access Direct Access n = relative block number read next write next reset no read after last write (rewrite) read n write n position to n read next write next rewrite n
Operations Performed on Directory n n n Search for a file Create a file Delete a file List a directory Rename a file Traverse the file system
Protection n File owner/creator should be able to control: p p n what can be done by whom Types of access p p p Read Write Execute Append Delete List
Opening a file n Working with files requires us to use file pointers To declare a file pointer: FILE *fp; To open a file: file. Pointer = fopen(file. Name, mode); Both filename and mode are type char* (char pointers aka strings) n n File pointer will be set to NULL when opening files You should always verify that the file was opened successfully 2016 12
NULL pointer n n n A pointer that does not refer to a valid object Behavior undefined Often used to indicate pointers not in use or failed operations p p p n n End of a list (advanced data structures) Memory allocation failed (dynamic memory management) Opening file failed Search for substring failed (strstr from string. h) Assigning pointer to NULL avoids unintentional access to released resources May lead to segmentation fault when accessed NULL is a pointer, 0 is an integer. NULL pointer may not always be zero, but typically is. 2016 13
Parameters for fopen n Modes: p p p n "r " – read "w" – write (when the file already exists, it will be overwritten. If there is no file, it will be created) "a" – append (write to the end of an existing file) File name: p p p Full name of the file (name + extension if it exists) as a string (char*) The file will be looked for in the same directory as the executable (relative path) You can also use a full path to the file 2016 14
Code example n You should always check if the file was successfully opened When opening of the file fails, reading from it will crash the program. FILE *fi; // file pointer declaration char input. File[] = {"numbers. txt"}; fi = fopen(input. File, "r"); //opening file if (fi == NULL) // check for errors { exit(1); // abort. Exit comes from stdlib. h } 2016 15
Closing a file n n Resources should be freed when not needed All of the files should be closed before exiting When writing, any files not closed may have parts or all of the content missing from it. Closing writes the output still in buffer to the file. Especially important when writing log files and the program crashes. To close a file: fclose(file. Pointer); 2016 16
Functions with files n n n fscanf(file. Pointer, format, …); read formatted text from a file fgets(destination, length, file. Pointer); read line by line or until length is exceeded fprintf(file. Pointer, format, …); write formatted text to a file fputs(contents, file. Pointer); write line by line to a file feof(file. Pointer); Check if the end-of-file indicator is set EOF - a constant to indicate the end of file. Typically -1 2016 17
Example- reading using EOF #include <stdio. h> int main(void) { FILE *fi; int temp; char input. File[] = {"numbers. txt"}; fi = fopen(input. File, "r"); while (fscanf(fi, "%d", & temp) != EOF) { printf("Got: %dn", temp); } fclose(fi); return 0; } 2016 18
Example- reading using count #include <stdio. h> #define INPUT_FILE "numbers. txt" int main(void) { FILE *fi = fopen(INPUT_FILE, "r"); int used, quota; while (fscanf(fi, "%d %d", &used, "a) == 2) printf("User is using %d, quota was %dn", used, quota); fclose(fi); return 0; } 2016 19
Example - writing to the file #include <stdio. h> #define LIMIT 5 int main(void) { FILE *fo = fopen(“numbers 2. txt", "w"); int i; for (i = 0; i < LIMIT; i++) fprintf(fo, "Output: %dn", i); fclose(fo); return 0; } 2016 20
External sorting files(bonus task 4 p) F 97 20 53 04 32 15 50 89 48 95 04 37 n = 12 F 1 97, 04 32 48 95 F 2 20 53, 15 50 89, 04 37 F 3 20 53 97, 04 37 F 4 04 15 32 48 50 89 95 F 1 04 15 20 32 48 50 53 89 95 97 F 2 04 37 F 3 04 04 15 20 32 37 48 50 53 89 95 97 F 4
STRUCTURES
STRUCTURES n n Complex data type It consist of other data types (int, char, float etc) typedef struct employee { int employee. Code; char first. Name[15]; char last. Name[15]; float salary; } employee;
Structure in the memory struct employee { int employee. Code; char first. Name[15]; char last. Name[15]; float salary; }; 0 4 19 empl. Co first. Name last. Name 36 salary Structure size in memory = the size of its members + padding In this case, the structure is 38 bytes + padding 2016 24 39
Accessing structure members n Stucture member names are united by points with the structure variable name. structure. Variable. Name. member. Name manager. salary = 15. 5; printf("%f", manager. salary); employees[5]. salary = manager. salary; strcpy(employees[5]. first. Name, "Indrek"); • You can assign structures as a whole employee manager, staff[20], employees[10]; employees[0] = manager; employees[5] = staff[15]; 2016 25
Example #include <stdio. h> #include <math. h> typedef struct point { int x; int y; } point; int main(void) {double length; point segment[2]; printf("Enter the start and the ending of a line segment x 1 y 1 x 2 y 2n"); scanf("%d%d", &segment[0]. x, &segment[0]. y, &segment[1]. x, &segment[1]. y); length=sqrt(pow(segment[1]. x - segment[0]. x, 2)+pow(segment[1]. y segment[0]. y, 2)); printf(„The segment length is %lgn", length); return 0; } 2016 26
Example - Initializing a structure 1 #include <stdio. h> 2 3 typedef struct product 4 { 5 float price; 6 char name[30]; 7 } product; 8 9 int main(void) 10 { 11 product item = {. price = 0. 50, . name = "Apple"}; 12 product items[] = {{0. 35, "Bread"}, {0. 90, "Tomato"}}; 13 printf("%. 2 f eur - %sn", item. price, item. name); 14 printf("%. 2 f eur - %sn", items[0]. price, items[0]. name); 15 printf("%. 2 f eur - %sn", items[1]. price, items[1]. name); 16 return 0; 17 } 2016 27
Nested structures • You can put one structure inside of another • The order they’re defined is important 2016 typedef struct date { unsigned day; unsigned month; unsigned year; } date; typedef struct person { char f. Name[15]; char l. Name[15]; date contract. Signed; } person; 28
Function returning a structure n n Reminder: structure was a data type, albeit a complex one. This means that we can also use it as a return type for a function. We can return one whole structure per function call. We could also return a structure pointer as we’ll see in a few weeks typedef struct point { A prototype for a function point enter. Point() int x, y; } point; point enter. Point(){ point temporary; temporary. x = 5; temporary. y = 7; return temporary; } 2016 29
Pointer operations n int *p // declare a pointer variable n &var // get the location of the variable(mem address) n *p n p = &var // assigning the address of var to pointer p n *p = 55 // assign a value to the dereferenced pointer n printf("%p", p) // printing out the address stored in var p n printf("%d", *p) // printing out the value that p points to 2016 // dereferencing a pointer 30
Pointers and arrays visualized int array[] = {5, 3, 7, 3, 5}; int *p; *p p = array; 48 F 9 AC 9 1 array[0] array[1] array[2] array[3] array[4] 5 3 7 3 5 *(p + 0) *(p + 1) *(p + 2) *(p + 3) *(p + 4) 2016 31
Pointers and structures You can point to the start of a structure or an element inside it. typedef struct employee{ int employee. Code; char first. Name[15]; char last. Name[15]; float salary; } employee; employee manager; employee *p. Str; p. Str = &manager; 2016 32
Accessing members using pointers Both of these are equal (*p. Str). employee. Code; (*p. Str). f. Name; (*p. Str). l. Name; (*p. Str). salary; 2016 p. Str->employee. Code; p. Str->f. Name; p. Str->l. Name; p. Str->salary; 33
Example with pointers #include <stdio. h> #include <string. h> typedef struct employee {int employee. Code; char f. Name[15]; char l. Name[15]; float salary; } employee; void print. Employee(employee *p. Str); int main(void) { employee manager = {775, "Ants", "Kukk", 555. 55}; print. Employee(&manager); return 0; } void print. Employee(employee *p. Str) {printf("Employee %06 d, %s %s, earns %2. 2 f per week", p. Str->employee. Code, p. Str->f. Name, p. Str->l. Name, p. Str->salary); } 2016 34
Header files(1) n n n For a larger project it makes sense to break the program code into several files. Custom datatypes and function prototypes are moved into. h header files. The implementation of these functions remains in the. c code files. In order to use datatypes or functions of another module you have to: 1. 2. include the corresponding header file to your code file tell the compiler to compile the code file where the functionality has been implemented as well IAG 0582 35
Header files (2) tst. h typedef struct typename{ int a; float b; char s[10]; } test_struct; void print. All(int n, struct typename *M); tst. c #include <stdio. h> #include "tst. h" void print. All(int n, struct typename *M){ int i; for(i = 0; i < n; i++) printf("%sn", M[i]. s); } IAG 0582 36
Header files (3) main. c #include "tst. h" int main(void){ test_struct M[2] = {12, 3. 7, "Thomas", 14, 4. 4, "Matthew"}; print. All(2, M); } Compiling: gcc main. c tst. c -o test -Wall Running: . /test IAG 0582 37
Binary files (1) n n n Binary files are files that contain data the way it is stored in computer memory. Some parts of binary files may be human readable but it is not their primary purpose. Data in a binary file is not editable without a specialized editor. If the binary file contains records of a single type then it is very easy to read and write data to that file using functions fread() and fwrite(). IAG 0582 38
Binary files (2) n n Function fwrite() attempts to write nmemb number of elements from an array pointed to by ptr into a file stream. It returns the number of elements it successfully managed to write. Basically the function writes size * nmemb number of bytes from memory straight to file. The sizeof() keyword is useful for determining the size of a single element. size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) IAG 0582 39
Binary files (3) n n Function fread() attempts to read nmemb elements from file stream into an array pointed to by ptr. It returns the number of elements it managed to read. Basically the (partial) contents of the file are copied straight to memory. size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) IAG 0582 40
Binary files (4) int load. Data(int max, struct data *D, char *filename) { FILE *f = fopen(filename, "rb"); if(f == NULL) { printf("Couldn't load data from file %s. n", filename); return 0; } int k = fread(D, sizeof(struct data), max, f); fclose(f); return k; } IAG 0582 41
Binary files (5) void save. Data(int n, struct data *D, char *filename) { FILE *f = fopen(filename, "wb"); if(f == NULL) { printf("Couldn't save data to file %s. n", filename); return; } fwrite(D, sizeof(struct data), n, f); fclose(f); } IAG 0582 42
- Slides: 43