-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.c
More file actions
81 lines (69 loc) · 1.7 KB
/
utils.c
File metadata and controls
81 lines (69 loc) · 1.7 KB
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
72
73
74
75
76
77
78
79
80
81
#include "utils.h"
#include "common.h"
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
void send_message(int sock, const char *msg) {
write(sock, msg, strlen(msg));
usleep(1000);
}
int read_input(int sock, char *buffer, int size) {
memset(buffer, 0, size);
int n = read(sock, buffer, size);
if (n > 0) {
buffer[strcspn(buffer, "\n")] = 0;
return 1;
}
return 0;
}
int get_next_id_csv(const char *csv_path) {
FILE *fp = fopen(csv_path, "r");
if (!fp) return 1;
char line[512];
int max_id = 0;
fgets(line, sizeof(line), fp);
while (fgets(line, sizeof(line), fp)) {
int id;
if (sscanf(line, "%d,", &id) == 1 && id > max_id) {
max_id = id;
}
}
fclose(fp);
return max_id + 1;
}
int lock_file(int fd, int lock_type) {
struct flock lock;
lock.l_type = lock_type;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = getpid();
if (fcntl(fd, F_SETLKW, &lock) == -1) {
perror("Error acquiring lock");
return -1;
}
return 0;
}
int unlock_file(int fd) {
struct flock lock;
lock.l_type = F_UNLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = getpid();
if (fcntl(fd, F_SETLK, &lock) == -1) {
perror("Error releasing lock");
return -1;
}
return 0;
}
// NEW: Trim whitespace from strings
void trim_string(char *str) {
int len = strlen(str);
while (len > 0 && (str[len-1] == ' ' || str[len-1] == '\t' ||
str[len-1] == '\n' || str[len-1] == '\r')) {
str[len-1] = '\0';
len--;
}
}