Update line in text file using C/C++

  • sandyirwan
  • Newbie
  • Newbie
  • sandyirwan
  • Posts: 5

Post 3+ Months Ago

Hi,

I need some hlp on manipulating a text file using C/C++. I have a text file containing lines of fields with space " " as the deliminator & each line ends with a "#" as follows:-

name01 address01 telNo01 zip01#
name02 address02 telNo02 zip02#
name03 address03 telNo03 zip03#

and i would like to change it to the following:-

name01 address01 telNo01 zip01#
name02 address04 telNo05 zip02#
name03 address03 telNo03 zip03#

i use fgets() to read the file, then use sscanf() to copy each field into a variable. Then I'll chg the appropriate field & would like to update the text file.


anyone can assist me on this?? :( need it urgently...
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • Managedlinks
  • Proficient
  • Proficient
  • Managedlinks
  • Posts: 294

Post 3+ Months Ago

you will need to write the entire file out because (I assume) each field is not of a fixed length. which makes random reads/writes hard.

simply write each each line with fprintf().

you will most likely want to open the input file
read each line
process it
write each line to a temp out file (modified or not)
after processing close the input file and output file
rename the input file to a tmp name,
rename the output file to the original name
unlink(delete) the tmp file

this way if something goes wrong no data is lost

Post Information

  • Total Posts in this topic: 2 posts
  • Users browsing this forum: No registered users and 121 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.