Replace wordA to wordB in a txt and then save it in a new file. MATLAB -


how write function take in following: filename: (a string corresponds name of file) worda , wordb: both 2 strings no space

the function should this: a- read txt file line line b- replace every occurrence of worda wordb. c- write modifified text file same original file, preprended 'new_'. instance, if input file name 'data.txt', output 'new_data.txt'.

here have done. has many mistakes got main idea. please find mistake , make function work.

function [ ] = replacestr( filename,worda, wordb ) % replace worda wordb in txt , save in new file.  newfile=['new_',filename] fh=fopen(filename, 'r') fh1=fgets(fh) fh2=fopen(newfile,'w') line='' while ischar(line)     line=fgetl(fh)     newline=[] while ~isempty(line)     [word line]= strtok(line, ' ') if strcmp(worda,wordb) word=wordb       end newline=[ newline word ''] end newline=[] fprintf('fh2,newline') end  fclose(fh) fclose(fh2)  end 

you can read entire file in string using fileread function (it calls fopen/fread/fclose underneath), substitute text, save @ once file using fwrite.

str = fileread(filename);               %# read contents of file string str = strrep(str, worda, wordb);        %# replace worda wordb  fid = fopen(['new_' filename], 'w'); fwrite(fid, str, '*char');              %# write characters (bytes) fclose(fid); 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -