| readLine_1.c | |
|---|---|
| 1 | #include<stdio.h> |
| 2 | #include<stdlib.h> |
| 3 | #include<unistd.h> |
| 4 | #include<fcntl.h> |
| 5 | #include<string.h> |
| 6 | #include<errno.h> |
| 7 | |
| 8 | #define FILE_NAME "qas" |
| 9 | #define MAX_LINE 200 |
| 10 | |
| 11 | char* readLine(int); |
| 12 | |
| 13 | int main(){ |
| 14 | |
| 15 | int fd; |
| 16 | int lineno = 1; |
| 17 | char *linebuf = NULL; |
| 18 | |
| 19 | fd = open(FILE_NAME, O_RDONLY); |
| 20 | if(fd < 0) { |
| 21 | perror(FILE_NAME); |
| 22 | return -1; |
| 23 | } |
| 24 | |
| 25 | while ((linebuf=readLine(fd)) != NULL ) { |
| 26 | printf(" %d: %s",lineno,linebuf); |
| 27 | lineno++; |
| 28 | free(linebuf); |
| 29 | } |
| 30 | |
| 31 | return 0; |
| 32 | |
| 33 | } |
| 34 | |
| 35 | /* Funtn defntin of readlin() */ |
| 36 | |
| 37 | char* readLine(int fd) { |
| 38 | char *buffer; |
| 39 | buffer = NULL; |
| 40 | signed int i; |
| 41 | int n,k = 0; |
| 42 | |
| 43 | buffer = (char*)malloc(1024); |
| 44 | |
| 45 | for(i = 0;(n = read(fd,buffer+i,1)) > 0;i++) { |
| 46 | |
| 47 | if(buffer[i] == ' ') { |
| 48 | k = k+1; |
| 49 | |
| 50 | if(i == 0) { // to avoid space in first postn |
| 51 | k = 0; |
| 52 | i = i-1; |
| 53 | } |
| 54 | |
| 55 | if(k > 1) |
| 56 | i = i-1; |
| 57 | } |
| 58 | |
| 59 | if(buffer[i] != '\n' && buffer[i] != ' ') { |
| 60 | k = 0; |
| 61 | } |
| 62 | |
| 63 | if(buffer[i] == '\n') { |
| 64 | buffer[i+1] = '\0'; |
| 65 | break; |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | if(n == 0) { |
| 70 | free(buffer); |
| 71 | return NULL; |
| 72 | } |
| 73 | |
| 74 | return buffer; |
| 75 | } |