C: Write to a specific line in the text file without searching -


hello have file text:

14  5 4 45 854 14  4  47 5 

i need write text specific line. example line number 4 (doesn't matter whether append text or rewrite whole line):

14  5 4 45 854 14 new_text 4  47 5 

i have found function fseek(). in documentation written


fseek(file pointer,offset, position);

"offset specifies number of positions (bytes) moved location specified bt position."


but not know number of bites. know number of lines. how that? thank you

i assume going doing many times single file, such better indexing position of each newline char, example use function this:

long *lineposfind(int filedes) {     long * lineposarr = malloc(500 * sizeof(long));     char tmpchar;     long linesread = 0;     long charsread = 0;     while(1 == read(filedes, &tmpchar, 1))     {         if (!(linesread % 500)         {             lineposarr = realloc(lineposarr, (linesread + 500) * sizeof(long));         }         if (tmpchar == '\n')         {             lineposarr[linesread++] = charsread;         }         charsread++;     }     return lineposarr; } 

then can save index of newlines repeated use.

after can use so:

long *lineindex = lineposfind(filedes); long fourthline = lineindex[3]; 

note have not checked code, written head may need fixes, also, should add error checking malloc , read , realloc if using code in production.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -