Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <fcntl.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/types.h>
- #include <unistd.h>
- #define LINES_COUNT 100
- typedef struct TableElement
- {
- int offset;
- int length;
- } TableElement;
- int main(int argc, char *argv[])
- {
- if (argc != 2)
- {
- printf("Bad input, expected: ./prog input.txt\n");
- exit(-1);
- }
- TableElement *table = (TableElement *) malloc(sizeof(TableElement) * LINES_COUNT);
- int handle = open(argv[1], O_RDONLY); //возвращает описатель файла, подаётся путь и флаги через OR (|)
- if (handle == -1) //в errno устанавливается значение
- {
- perror("Cannot open file\n"); //выводится ошибка, код которой в errno
- exit(-1);
- }
- int offset = 0, line_length = 0, line_count = 0;
- char symbol;
- ssize_t err_code = 0;
- while ((err_code = read(handle, &symbol, 1)) > 0) //возвращает число считанных байт
- {
- ++offset;
- ++line_length;
- if (symbol == '\n')
- {
- table[line_count + 1].offset = offset;
- table[line_count].length = line_length;
- line_length = 0;
- ++line_count;
- if (line_count >= LINES_COUNT)
- {
- fprintf(stderr, "Exceeding max file size\n");
- exit(-1);
- }
- }
- }
- if (err_code == -1)
- {
- perror("Cannot read file");
- exit(-1);
- }
- if (symbol != '\n')
- {
- table[line_count + 1].offset = offset;
- table[line_count].length = line_length;
- ++line_count;
- }
- if (lseek(handle, 0, SEEK_SET) == -1) //устанавливает указатель на смещение 0 от начала файла
- {
- perror("Cannot read file");
- exit(-1);
- }
- char *buffer = (char *) malloc(1024);
- while (1)
- {
- printf("Enter line number: ");
- int number;
- int n = scanf("%d", &number);
- if (n <= 0)
- {
- printf("Bad input\n");
- fflush(stdin);
- continue;
- }
- if (number == 0)
- break;
- if ((number < 0) || (number > line_count))
- {
- printf("Bad string number\n");
- continue;
- }
- if (lseek(handle, table[number - 1].offset, SEEK_SET) == -1)
- {
- perror("Cannot read file");
- exit(-1);
- }
- if (read(handle, buffer, table[number - 1].length) == -1)
- {
- perror("Cannot read file");
- exit(-1);
- }
- buffer[table[number - 1].length] = '\0';
- printf("%s\n", buffer);
- fflush(stdin);
- }
- free(table);
- free(buffer);
- close(handle);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement