Remove data from text file

This is a discussion on Remove data from text file within the C++ Programming forums, part of the General Programming Boards category; Hi Everyone, Got one question here, let say I used fstream to write my data (username, password) into a password.txt ...

  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,048
    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
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,274
    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, 04:44 PM
  2. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 02:19 PM
  3. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 04: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

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