Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rdemeter
GitHub Repository: rdemeter/so
Path: blob/master/lab2/io-02.c
221 views
1
#include <stdio.h>
2
#include <string.h>
3
#include <stdlib.h>
4
#include <sys/types.h>
5
#include <sys/stat.h>
6
#include <fcntl.h>
7
#include <unistd.h>
8
9
int main (void){
10
int fd;
11
char *buf;
12
ssize_t bytes_read;
13
14
/* alocam spatiu pentru buffer-ul de citire */
15
buf = malloc(101);
16
if (buf == NULL){
17
perror ("malloc");
18
exit (EXIT_FAILURE);
19
}
20
21
/* deschidem fisierul */
22
fd = open ("gabi.txt", O_RDONLY);
23
if (fd < 0) {
24
perror ("open gabi.txt");
25
exit (EXIT_FAILURE);
26
}
27
28
/* ne pozitionăm în fisier */
29
if (lseek (fd, -100, SEEK_END) < 0) {
30
perror ("lseek");
31
exit (EXIT_FAILURE);
32
}
33
34
/* citim ultimele 100 caractere in buffer */
35
bytes_read = read (fd, buf, 100);
36
if (bytes_read < 0) {
37
perror ("read");
38
exit (EXIT_FAILURE);
39
}
40
buf[bytes_read] = '\0';
41
42
/* afisam sirul citit */
43
printf("file contents [%d bytes]: \n%s\n", bytes_read, buf);
44
45
/* inchidem fisierul */
46
close (fd);
47
48
/* eliberam buffer-ul alocat */
49
free (buf);
50
return 0;
51
}
52
53