rewrite to file

This is a discussion on rewrite to file within the C Programming forums, part of the General Programming Boards category; i want that my prog will rewrite (update) to exsist file if it was found a string im searching for ...

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    13

    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 !

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,558
    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()
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 04:02 AM
  2. Making a LIB file from a DEF file for a DLL
    By JMPACS in forum C++ Programming
    Replies: 0
    Last Post: 08-02-2003, 08:19 PM
  3. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM
  4. Hmm....help me take a look at this: File Encryptor
    By heljy in forum C Programming
    Replies: 3
    Last Post: 03-23-2002, 09:57 AM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 01:58 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21