seems like working lab2
This commit is contained in:
93
lab_2/textlib.c
Normal file
93
lab_2/textlib.c
Normal file
@@ -0,0 +1,93 @@
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define RBUFSZ 4096
|
||||
#define WBUFSZ 4096
|
||||
|
||||
// Функция обработки текста
|
||||
long long process_text(const char *in_path, const char *out_path, long long cap) {
|
||||
int in_fd = open(in_path, O_RDONLY);
|
||||
if (in_fd < 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
mode_t filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
|
||||
int out_fd = open(out_path, O_CREAT | O_WRONLY | O_TRUNC, filePerms);
|
||||
if (out_fd < 0) {
|
||||
close(in_fd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
char rbuf[RBUFSZ];
|
||||
char wbuf[WBUFSZ];
|
||||
size_t wlen = 0;
|
||||
|
||||
long long total_replacements = 0;
|
||||
int at_line_start = 1;
|
||||
unsigned char line_key = 0;
|
||||
int replacing_enabled = 1;
|
||||
|
||||
for (;;) {
|
||||
ssize_t n = read(in_fd, rbuf, sizeof(rbuf));
|
||||
if (n > 0) {
|
||||
for (ssize_t i = 0; i < n; i++) {
|
||||
unsigned char c = (unsigned char) rbuf[i];
|
||||
|
||||
if (at_line_start) {
|
||||
line_key = c;
|
||||
at_line_start = 0;
|
||||
}
|
||||
|
||||
unsigned char outc = c;
|
||||
if (c == '\n') {
|
||||
at_line_start = 1;
|
||||
} else if (replacing_enabled && c == line_key) {
|
||||
if (total_replacements < cap) {
|
||||
outc = ' ';
|
||||
total_replacements++;
|
||||
if (total_replacements == cap) {
|
||||
replacing_enabled = 0;
|
||||
}
|
||||
} else {
|
||||
replacing_enabled = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (wlen == sizeof(wbuf)) {
|
||||
ssize_t wrote = write(out_fd, wbuf, wlen);
|
||||
if (wrote < 0 || (size_t) wrote != wlen) {
|
||||
close(in_fd);
|
||||
close(out_fd);
|
||||
return -1;
|
||||
}
|
||||
wlen = 0;
|
||||
}
|
||||
wbuf[wlen++] = (char) outc;
|
||||
}
|
||||
} else if (n == 0) {
|
||||
if (wlen > 0) {
|
||||
ssize_t wrote = write(out_fd, wbuf, wlen);
|
||||
if (wrote < 0 || (size_t) wrote != wlen) {
|
||||
close(in_fd);
|
||||
close(out_fd);
|
||||
return -1;
|
||||
}
|
||||
wlen = 0;
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
close(in_fd);
|
||||
close(out_fd);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
close(in_fd);
|
||||
close(out_fd);
|
||||
|
||||
return total_replacements;
|
||||
}
|
||||
Reference in New Issue
Block a user