Created
April 10, 2021 06:24
-
-
Save alsamitech/7ee7471d525e101bcc76c380188d7519 to your computer and use it in GitHub Desktop.
Gets a specified line from a file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| // Types and stuff | |
| #include <ctype.h> | |
| #include <stdint.h> | |
| typedef struct _arr{ | |
| char* arr; | |
| size_t len; | |
| }; | |
| typedef struct _arr arr_t; | |
| char* read_file(char* filenm, long unsigned int* len){ | |
| char* buf=0; | |
| FILE* f=fopen(filenm, "rb"); | |
| if(f){ | |
| fseek(f,0,SEEK_END); | |
| *len=ftell(f); | |
| fseek(f,0,SEEK_SET); | |
| buf=(char*)calloc(1, *len); | |
| if(buf) | |
| fread(buf, 1, *len, f); | |
| fclose(f); | |
| } | |
| return buf; | |
| } | |
| char** atokl(char* InC, char* delim, long unsigned int* len){ | |
| char** tok=(char**)malloc(2*sizeof(char*)); | |
| //printf("%p\n", tok); | |
| tok[0]=strtok(strdup(InC), delim); | |
| { | |
| int i=1; | |
| while(tok[i-1]!=NULL){ | |
| tok=(char**)realloc(tok, (i+1)*sizeof(char*)); | |
| tok[i]=strtok(NULL, delim); | |
| //printf("%p\n", tok[i]); | |
| i++; | |
| } | |
| *len=i; | |
| /*EBRACE*/} | |
| return tok; | |
| } | |
| int main(int argc, char** argv){ | |
| if(argc<3){ | |
| printf("Usage: %s <filenm> <line_num>\n"); | |
| return 0; | |
| } | |
| arr_t f; | |
| f.arr=read_file(argv[1], &f.len); | |
| if(!f.arr){ | |
| #ifdef __unix__ | |
| puts("\033[1;31mCannot read file! Check filenm.\033[0m"); | |
| #else | |
| puts("Cannot read file! Check filenm."); | |
| #endif | |
| } | |
| int ln=atoi(argv[2]); | |
| arr_t lines; | |
| lines.arr=atokl(f.arr, "\n", &lines.len); | |
| puts(((char**)lines.arr)[ln]); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment