-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.c
71 lines (62 loc) · 1.36 KB
/
io.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* @file io.c
* @author Samuel Stolarik (xstola03)
* @brief 2nd part of DU2 IJC
*
* @date 2022-04-10
*
*/
#include <stdio.h>
#include <ctype.h>
/**
* @brief Function read one word of maximum size "max - 1"
* and stores it to the address pointed to by "s"
* word will be ended with \0
*
*
* @param s
* @param max
* @param f
* @return int number_of_characters read
*/
int read_word(char *s, int max, FILE *f)
{
if (f == NULL){
fprintf(stderr, "Invalid file given.\n");
return 0;
}
if (s == NULL){
fprintf(stderr, "Adress at \"s\" is not valid.\n");
return 0;
}
if (max == 0){
return 0;
}
static int err_count = 0;
int c;
int read_chars=0;
while((c = getc(f)) != EOF)
{
if (isspace(c) && read_chars == 0){
continue;
}
else if (isspace(c) && read_chars != 0){
break;
}
else
{
if (read_chars >= max -1){
if (err_count == 0){ //print the error msg only once
fprintf(stderr, "Word size limit reached.\n");
err_count++;
}
break;
}
s[read_chars++] = c;
}
}
if (read_chars == 0)
return EOF;
s[read_chars] = '\0';
return read_chars;
}