How to read in the last word in a text file and into another text file in C? -


so i'm supposed write block of code opens file called "words" , writes last word in file file called "lastword". have far:

file *f;  file *fp; char string1[100]; f = fopen("words","w");  fp=fopen("lastword", "w"); fscanf(f,    fclose(fp) fclose(f); 

the problem here don't know how read in last word of text file. how know word last word?

this similar tail tool does, seek offset end of file , read block there, search backwards, once meet whitespace or new line, can print word there, last word. basic code looks this:

char string[1024]; char *last; f = fopen("words","r"); fseek(f, seek_end, 1024); size_t nread = fread(string, 1, sizeof string, f); (int = 0; < nread; i++) {     if (isspace(string[nread - 1 - i])) {         last = string[nread - i];     } } fprintf(fp, "%s", last);     

if word boundary not find first block, continue read second last block , search in it, , third, until find it, print characters after position.


Comments

Popular posts from this blog

ios - Memory not freeing up after popping viewcontroller using ARC -

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -