pr2 Eng TTY 24 c5
pr2 Eng TTY 24 c5
ee/~lembit/prog2/
PROGRAMMING II
Tallinn 2024
PASS POINTS(before may 61pre after 50n)
40tests+(16+20)labs+10bonus=86
1 2 3 4
bonus
Lab 1
tests lab2
FINAL RESULT 65we+15hw1+15hw2+10hw10=105
HW 3
3
HW 1
HW 2
Written
exam
1 2 3 4
WE=code+theory question
Possible groups and levels
R.Heinsaar &co=> ICT121
V.Viies&co=>ICT122
File Concept
Access Methods
Directory Structure
File-System Mounting
File Sharing
Protection
File Concept
Types:
Data
numeric
character
binary
Program
File Structure
None - sequence of words, bytes
Simple record structure
Lines
Fixed length
Variable length
Complex Structures
Formatted document
Relocatable load file
Can simulate last two with first method by
inserting appropriate control characters
Who decides:
Operating system
Program
File Attributes
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
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
Several pieces of data are needed to manage
open files:
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
File Types – Name, Extension
Access Methods
Sequential Access
read next
write next
reset
no read after last write
(rewrite)
Direct Access
read n
write n
position to n
read next
write next
rewrite n
n = relative block number
Sequential-access File
Simulation of Sequential Access on a Direct-access File
Example of Index and Relative Files
A Typical File-system Organization
Operations Performed on Directory
Search for a file
Create a file
Delete a file
List a directory
Rename a file
Traverse the file system
Organize the Directory (Logically) to Obtain
Types of access
Read
Write
Execute
Append
Delete
List
Access Lists and Groups
Mode of access: read, write, execute
Three classes of users
RWX
a) owner access 7 111
RWX
b) group access 6 110
RWX
c) public access 1 001
Ask manager to create a group (unique name), say G, and add
some users to the group.
For a particular file (say game) or subdirectory, define an
appropriate access.
IAG0582 23
Accessing files
Files are an external resource.
In the case of such resources it is necessary to
explicitly set up a connection to the resource.
This means:
1. opening the connection;
2. doing something via the connection (like read or
write);
3. shutting down the connection after you're done.
IAG0582 24
Opening a file
Function fopen() is used for opening a file.
It requires 2 parameters, the name or path to
the file and access mode, which specifies
whether the file is opened for reading ("r"),
writing ("w") or appending ("a") data.
The function returns a pointer to FILE structure
that is used by all subsequent calls to that file.
If the function fails (for example, when reading
from a file that doesn't exist or trying to create a
file with the same name as an existing folder)
NULL pointer is returned instead.
IAG0582 25
Opening a file (2)
FILE *fopen(const char *filename, const char *mode)
//Example:
FILE *f;
//open file test.txt for reading
f = fopen("test.txt", "r");
if(f == NULL) //file could not be opened
exit(0); //exit the program
IAG0582 26
Position in file
Files are sequential access, reading and writing
advances the position you're at in the file.
This is the legacy of the time when files used to
be stored on external magnetic tape devices,
where indeed tape had to be winded for the
read or write to occur.
Function rewind() is used to get back to the
beginning of the file.
IAG0582 27
Reading from a file
Function fscanf() is used for reading formatted
input. It behaves just like scanf(), except first
parameter must be the FILE pointer. It returns
the number of variables it was able to
successfully fill out according to the format.
IAG0582 28
Reading from a file (2)
Function fgets() reads a line from the file
including the end of line symbol(s). The
parameters are the string to store the text,
length of that string and FILE pointer. If the
function fails it returns a NULL pointer.
IAG0582 29
Reading from a file (3)
//Example:
int x; //define some variables
char buf[200];
FILE *f = fopen("test.txt", "r"); //open for reading
if(f != NULL){ //if succesful
if (fscanf(f, "%d", &x) == 1) //if read succeeded
printf("%d\n", x); //then print
else if (!feof(f)){ //else if not yet fileend
fgets(buf, 200, f); //read to buffer
printf(buf); //print that
}
fclose(f); //close file
}
IAG0582 30
Writing to a file
Function fprintf() is used for writing formatted
output to a file. Behaves just like printf(), except
first parameter must be the FILE pointer.
IAG0582 31
Writing to a file (2)
//Example:
FILE *f=fopen("test.txt","w");//open for writing
if(f != NULL){ //did fopen succeed?
fprintf(f, "High %d!\n", 5);//write to file
fputs("Some text.");
fclose(f);
//close file
}
IAG0582 32
Closing the file
Function fclose() is used for closing the
connection to file. Any read or write after fclose()
will fail.
IAG0582 33
Header files
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. include the corresponding header file to your
code file
2. tell the compiler to compile the code file where
the functionality has been implemented as well
IAG0582 34
Header files (2)
tst.h
typedef struct typename{
int a;
float b;
char s[10];
} test_struct;
void printAll(int n, struct typename *M);
tst.c
#include <stdio.h>
#include "tst.h"
void printAll(int n, struct typename *M){
int i;
for(i = 0; i < n; i++)
printf("%s\n", M[i].s);
}
IAG0582 35
Header files (3)
main.c
#include "tst.h"
int main(void){
test_struct M[2] = {12, 3.7, "Thomas", 14, 4.4,
"Matthew"};
printAll(2, M);
}
Compiling:
gcc main.c tst.c -o test -Wall
Running:
./test
IAG0582 36
Shell sort algorithm (1)
(has less exchanges, presumes that data is partially sorted)
External sorting files(bonus task 4p)
F 97 20 53 04 32 15 50 89 48 95 04 37 n = 12
F1 97, 04 32 48 95
F2 20 53, 15 50 89, 04 37
F3 20 53 97, 04 37
F4 04 15 32 48 50 89 95
F1 04 15 20 32 48 50 53 89 95 97
F2 04 37
F3 04 04 15 20 32 37 48 50 53 89 95 97
F4
End of file system
Structures
Structures are used for grouping different
datatypes together into a single unit. It's
possible to declare a single variable as a
structure but usually the aim is to declare a new
datatype and then use this datatype for
declaring many variables.
//Example: single variable
struct {
int a;
float b;
char s[10];
} x;
IAG0582 40
Structures (2)
//Example: datatype
struct typename{
int a;
float b;
char s[10];
} ;
IAG0582 41
Structures (3)
In order to access fields of a structure record
selector . is used after the variable name.
C permits assignment operation for structures.
This assignment copies over all fields in the
structure.
//Example:
x.a = 14;
strcpy(x.s, "hello");
M[5] = x;
printf(M[5].s);
IAG0582 42
Structures and pointers
If a structure variable is of a pointer type then
the record selector changes to ->
Arrays are always pointers to the first element in
the array. When it comes to function parameters
then there's no difference between declaring a
parameter a pointer or an array.
//Example:
void printAll(int n, struct typename *M){ //could be: M[]
int i;
for(i = 0; i < n; i++)
printf("%04d %s\n", M[i].a, M[i].s);
}
void printFirst(struct typename *M){
printf("%04d %s\n", M->a, M->s); //could be: M[0].x, M[0].s
}
IAG0582 43
Typedef
It quickly becomes annoying to always type
"struct typename" when declaring a variable.
Typedef can be used to give the type a new and
shorter name.
//Example:
typedef struct typename{
int a;
float b;
char s[10];
} test_struct;
test_struct x;
IAG0582 44