Mail Archives: djgpp/2003/05/21/19:45:11
"Alex O" <Alex AT compuweigh DOT com> escribió en el mensaje
news:795DD3C2E97585449DCDEEE79CCD5C22BB5D AT email2k DOT compuweigh DOT com..
.
> Hi everybody,
>
> Can somebody explain me what is wrong with the following code
snippet?
> The reason I am asking is because the original file WATTCP.CFG
never gets changed!
> As you can see, I tried two different functions to write data to
the file and each one of those returned the correct number of
characters written,
> but when I go to view the file it is not even touched (even the
file date is not changed). How come?
>
> BTW, does fgets() move the file pointer as it advances?
>
> ..
> if( (ptr = fopen("wattcp.cfg", "r+")) != NULL )
> {
> while( fgets(tmp_buf, 99, ptr) )
> {
> //Skip the comment lines
> if( tmp_buf[0] != '#' )
> {
> if( !strncmp(tmp_buf, "my_ip = ", 8) )
> {
> _inet_ntoa((CHAR *)ip_buf, nonvol->IP_Addr);
> n = fprintf(ptr, "my_ip = %s ; mandatory\n", ip_buf);
> }
> else if( !strncmp(tmp_buf, "netmask = ", 10) != NULL )
> {
> _inet_ntoa((CHAR *)ip_buf, nonvol->Subnet_Mask);
> sprintf(tmp_buf, "netmask = %s ; mandatory if not
using DHCP\n", ip_buf);
> n = fwrite(tmp_buf, sizeof(BYTE), strlen(tmp_buf),
ptr);
> }
> }
> }
> fclose(ptr);
> }
> ..
>
> Thanks for any good advice how to make this thing work.
>
> Regards,
>
> Alex Oleynikov
In the info file of libc, fopen node, I read
"If the file is open for both reading and writing, you must call
'fflush', fseek' or 'rewind' before switching from read to write
or from write to read"
OTOH, your approach is dangerous. If the length of lines is not
fixed, you can overwrite part of next line before this be readed.
If this is not the case, (ie, the length is fixed), you must
synchronize carefully the reads/writes.
A better solution, (IMHO):
Open you file for read, and create a new file, and copy line to
line. When you find the relevant part to be changed, write it in
the second file. Finally, you can delete the original file and
rename the second.
HTH
--
José L. Sánchez Garrido
- Raw text -