Read and write in the same file

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Oct 2008
Posts: 5
Reputation: dusse is an unknown quantity at this point 
Solved Threads: 0
dusse dusse is offline Offline
Newbie Poster

Read and write in the same file

 
0
  #1
Nov 27th, 2008
Hello guys,

How can I read and write in the same file? I want to open a file that exists and write something in the end of each line of the file..

Ex:
My_file:
a b c
d e f
g h i

I want to alter to:
a b c XX
d e f XX
g h i XX

I tried this but the file does not altered..
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main()
  5. {
  6. FILE *f;
  7. f = fopen("file.txt", "a+");
  8.  
  9. while (fgets(line,sizeof(line),f)){
  10. fputc("XX",f);
  11. }
  12.  
  13. fclose(f);
  14. return 0;
  15. }
I tried a lot of thing like open in other modes, and nothing

thanks
Last edited by Ancient Dragon; Nov 27th, 2008 at 10:05 pm. Reason: add code tags
Reply With Quote Quick reply to this message  
Join Date: Dec 2005
Posts: 5,850
Reputation: Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute 
Solved Threads: 751
Team Colleague
Salem's Avatar
Salem Salem is offline Offline
Void main'ers are DOOMed

Re: Read and write in the same file

 
0
  #2
Nov 27th, 2008
Well since the file is stored as
a b c\nd e f

What's going to happen to the 2nd line when you add XX to the first?

There is no "insert" function for a file.

Unless you're replacing N bytes with N bytes, you need to read from one file, and write to another.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



Tag cloud for C
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC