Thread: Remove data from text file

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    58

    Remove data from text file

    Hi Everyone,
    Got one question here, let say I used fstream to write my data (username, password) into a password.txt files, how can I remove the particular user from the txt file when need to?

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You need to read the entire file into memory, remove whatever data you want, and then write the file's data back to the disk.

    I recommend writing to a temporary file, and then remove()ing the old file and rename()ing the new file to the old name. That way, if your program is interrupted while writing the data out to the file, the old file will still be in existence rather than being deleted. [edit] Those are C functions: include <cstdio>. [/edit]
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by dwks View Post
    You need to read the entire file into memory, remove whatever data you want, and then write the file's data back to the disk.
    Not necessarily. If the format is for one entry per every line, then you only ever have to hold a single line in memory. Read a line -- if the line is for the user you want to delete, skip it. Otherwise, write it to the output file. Repeat. At the end, remove the original and rename the output back.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  2. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  3. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. File Database & Data Structure :: C++
    By kuphryn in forum C++ Programming
    Replies: 0
    Last Post: 02-24-2002, 11:47 AM