From: Can Baran on
TideMan <mulgor(a)gmail.com> wrote in message <39c61098-7287-4df5-b762-5382036e1a7c(a)u34g2000yqu.googlegroups.com>...
> On Apr 7, 8:58 am, "Can Baran" <can_bara...(a)yahoo.com> wrote:
> > bcb <bbow...(a)bigelow.org> wrote in message <821h9tFsm...(a)mid.individual.net>...
> > > On Tue, 06 Apr 2010 19:13:05 +0000, Can Baran wrote:
> >
> > > > Hey guys,
> > > > So, I want to overwrite some lines in a txt file via fopen. so
> > > > fid = fopen(myfile, 'w+');
> > > > cur_line = fgetl(di);
> > > > while ischar(cur_line)
> > > > %if changeable(cur_line)
> > > > %change it
> > > > end
> > > > fclose(fid)
> > > > however when i open with w+ (to overwrite), fgetl always returns -1.
> > > > Why? I read the help it says:
> > > > the line contains only the end-of-file marker. In this case, tline is
> > > > the numeric value -1. How can I go line by line after opening a file
> > > > with w+ or
> > > > how can I overwrite a txt file if I open it with r+ Can
> >
> > > Did you read the help for fopen?
> >
> > > 'w+'       Open or create new file for reading and writing. **Discard        
> > >            existing contents, if any.**  (emphasis mine)
> >
> > > fgetl returns -1 because there is no data in the file anymore...
> >
> > > pidgen code
> >
> > >    open old file
> > >    open new file
> > >    while there's data in the old file
> > >            read old file
> > >            change data as appropriate
> > >            write new file
> > >    when done, rename new file to old file
> >
> > > Bruce
> >
> > Bruce,
> >  you see that you write each line of the old file to the new file
> > what i want to do is i dont want to create a new file, i want to parse the old file until i find the thing i am interested in then i want to change that in the **old file** and break the while loop and output the old file
> > and yes i did read the help for fopen, but what does it mean that it discards existing contents? I thought that enables you to overwrite it.
> > Currently i am implementing my code the way you recommend it in your pseudo-code, but there should be a better way of doing this (i.e. without creating a new file, changing the old file)
>
> Well, one way is to read the entire file in using:
> fid=fopen(myfile,'rt');
> a=fscanf(fid,'%c');
> fclose(fid);
> fid=fopen(myfile,'wt');
> Now, you use strrep to replace strings in a as required, then:
> fprintf(fid,'%c',a);
> fclose(fid);

Bruce,
I found out about a better way of dealing with this
SED command
cmd = sprintf('sed "s/s1/s1/" <old >new', old_string, new_string);
dos(cmd)
it s faster
can