Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <poll.h>
- #define BUF_SIZE 32
- int main(int argc, char **argv) {
- int file = 0;
- ssize_t bytesRead = 0;
- void *buf[BUF_SIZE];
- int *stringStart;
- int *stringLength;
- int i = 0;
- int stringNumber = 1; // Nomer stroki
- int absolutePosition = -1; // Pozitsiya v fajle
- char *s;
- struct pollfd fds[1];
- char c;
- fds[0].fd = 0; // stdin
- fds[0].events = POLLIN;
- fds[0].revents = 0;
- stringStart = (int *)malloc(sizeof(int)*2);
- stringLength = (int *)malloc(sizeof(int)*2);
- stringStart[0] = 0; // Fiktivnaya 0-aya stroka
- stringStart[1] = 0; // Stroki nachinayutsya s 1
- stringLength[0] = 0;
- stringLength[1] = 0;
- // Open file
- if (argv[1] == NULL) {
- printf("Ne ukazan fajl\n");
- return -1;
- }
- file = open(argv[1], O_RDONLY);
- if (file == -1) {
- printf("Ne udalos' otkryt' fajl\n");
- return -1;
- }
- // Read, make table
- while((bytesRead = read(file, buf, (size_t) BUF_SIZE)) > 0) {
- for(i = 0; i < bytesRead; i++) {
- absolutePosition++;
- // printf("%c", ((char *)buf)[i]);
- if(((char *)buf)[i] == '\n') {
- stringLength[stringNumber] = absolutePosition - stringStart[stringNumber];
- stringNumber++;
- stringStart = (int *) realloc(stringStart, sizeof(int)*(stringNumber + 1));
- stringLength = (int *) realloc(stringLength, sizeof(int)*(stringNumber + 1));
- stringStart[stringNumber] = absolutePosition + 1;
- }
- }
- }
- // stringNumber--;
- if (absolutePosition == -1) {
- printf("Razmer fajla 0\n");
- close(file);
- return 0;
- }
- /*
- // Print table
- for(i = 1; i < stringNumber; i++)
- printf("%d : %d : %d\n", i, stringStart[i], stringLength[i]);
- */
- /******************************************************
- ******************************************************/
- while(poll(fds, 1, 5000))
- if((i = atoi(gets(s))) > 0) {
- if(i < stringNumber) {
- char buf[stringLength[i] + 1];
- buf[stringLength[i]] = 0;
- lseek(file, (off_t)stringStart[i], SEEK_SET);
- read(file, buf, (size_t)stringLength[i]);
- printf("%s\n", buf);
- } else printf("Takoj stroki net\n");
- fds[0].revents = 0;
- }
- else {
- close(file);
- free(stringLength);
- free(stringStart);
- return 0;
- }
- // Vyvod vsego fajla
- for(i = 1; i < stringNumber; i++) {
- char buf[stringLength[i] + 1];
- buf[stringLength[i]] = 0;
- lseek(file, (off_t)stringStart[i], SEEK_SET);
- read(file, buf, (size_t)stringLength[i]);
- printf("%s\n", buf);
- }
- /******************************************************
- ******************************************************/
- // Finish
- close(file);
- free(stringLength);
- free(stringStart);
- return 0;
- }
Add Comment
Please, Sign In to add comment