Originally Posted by
Babkockdood
Think about this. printf, sprintf, and fprintf all work on streams, right? Just like scanf, sscanf, and fscanf work on streams?
When I use a function like rewind() or fseek() with SEEK_END, it changes where the stream position is, it changes where fprintf begins outputting, and where sscanf begins inputting.
So, since strings are streams, like files are, can I rewind a string like I can a file?
I guess I could write my string to a file and then use fscanf as a last resort, but I'm just wondering if there's an easier way. How would I go about writing a function like this myself?
To rewind a string all you have to do is put it back some where between where it is and the start of the string;
Code:
char buff[1024];
char *b = buff;
int x;
x = sprintf(b,"hello world %ld\n", (long)time(NULL));
if(x <= 0)
return;
b += x ;
x = sprintf(b,"hello world %d\n", b - buff);
if(x <= 0)
return;
b += x;
/*** to rewind the string pointed to by b ***/
b = buff;
x = sprintf(b,"hello world %d\n", b - buff);
if(x <= 0)
return;
/** will print "hello world 0\n" ***/
printf("%s\n", buff);