60 lines
1.2 KiB
C
60 lines
1.2 KiB
C
|
// functions that can move the file position conveniently
|
||
|
// remember that the last line of a file is usually empty and goes from '\n' to EOF
|
||
|
|
||
|
#include "move_lines.h"
|
||
|
#include <unistd.h>
|
||
|
|
||
|
// function to move back/up
|
||
|
void go_back_x_lines(int fd, int lines) {
|
||
|
for (int i = 0; i < lines; i++) {
|
||
|
seek_previous_line(fd);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void seek_previous_line(int fd) {
|
||
|
seek_line_start(fd);
|
||
|
lseek(fd, -1, SEEK_CUR);
|
||
|
seek_line_start(fd);
|
||
|
}
|
||
|
|
||
|
// set file position to the beginning of the line
|
||
|
void seek_line_start(int fd) {
|
||
|
char cur_char = '\0';
|
||
|
|
||
|
while (cur_char != '\n') {
|
||
|
int ret_lseek = lseek(fd, -1, SEEK_CUR);
|
||
|
if (ret_lseek == -1)
|
||
|
break;
|
||
|
|
||
|
read(fd, &cur_char, 1);
|
||
|
if (cur_char != '\n')
|
||
|
lseek(fd, -1, SEEK_CUR);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// function to move forward/down
|
||
|
void go_forward_x_lines(int fd, int lines) {
|
||
|
for (int i = 0; i < lines; i++) {
|
||
|
seek_next_line(fd);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void seek_next_line(int fd) {
|
||
|
seek_line_end(fd);
|
||
|
lseek(fd, 1, SEEK_CUR);
|
||
|
}
|
||
|
|
||
|
// set file position to the end of the line
|
||
|
void seek_line_end(int fd) {
|
||
|
char cur_char = '\0';
|
||
|
|
||
|
while (cur_char != '\n') {
|
||
|
// return code 0 of read indicates EOF
|
||
|
if (read(fd, &cur_char, 1) == 0)
|
||
|
break;
|
||
|
}
|
||
|
|
||
|
lseek(fd, -1, SEEK_CUR);
|
||
|
}
|
||
|
|