-
rewrite to file
i want that my prog will rewrite (update) to exsist file if it was found a string im searching for inside this file, so i did this:
Code:
fptr=fopen("data.txt","r+"); // i also tried "a+"
fscanf(fptr,"%s\n",tmp_name); //tmp_name is a vector.
if (strcmp(myname,tmp_name)==0)
{
fprintf("%d %d %f %d",won,lost,avg,best);
}
fclose(fptr);
my file is a txt file and looks like this:
name1
1 2 3.3 5
name2
1 2 3.3 5
and i want to chk if name1==myname then change the 1 2 3.3 5 to 7 8 9.9 5
did what i was doing is illigel ? coz i cant get it to work...(the fprintf is doing nothing..), or maybe some1 know other way to do this ?
thanks !
-
Performing an update on text files is really REALLY messy. If the line length changes at all, then you're sunk.
> fscanf(fptr,"%s\n",tmp_name);
Before this, you need to call ftell() to record where the start of that line is.
> fprintf("%d %d %f %d",won,lost,avg,best);
Before you call this, you need to call fseek() with the answer you got from ftell(), so you reposition the file pointer back to where the line started in the file.
Also, when switching between writing to the file, and reading it again, you should call fflush()