开发者

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

How could I write a function to take in the following: filename: (a string that corresponds to the name of a file) wordA and wordB: They are both two strings with no space

The function should do this: A- read the a txt file line by line B- replace every occurrence of wordA to wordB. C- Write the modifified text file with the same as the original file, but preprended with 'new_'. For instance, if the input file name was 'data.txt', the output would be 'new_data.txt'.

Here is what I have done. It has so many m开发者_Go百科istakes but I got the main idea. Could you please help to find my mistake and to make the function work.

function [ ] = replaceStr( filename,wordA, wordB )
% to replace wordA to wordB in a txt and then save it in a 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 the entire file in a string using the FILEREAD function (it calls FOPEN/FREAD/FCLOSE underneath), substitute text, then save it all at once to a file using FWRITE.

str = fileread(filename);               %# read contents of file into string
str = strrep(str, wordA, wordB);        %# Replace wordA with wordB

fid = fopen(['new_' filename], 'w');
fwrite(fid, str, '*char');              %# write characters (bytes)
fclose(fid);


Some things to fix:

  • It will be much easier to use the function STRREP instead of parsing the text yourself.
  • I would use FGETS instead of FGETL to keep the newline character as part of the string, since you will want to output them to your new file anyway.
  • The format of your FPRINTF statement is all wrong.

Here's a corrected version of your code with the above fixes:

fidInFile = fopen(filename,'r');            %# Open input file for reading
fidOutFile = fopen(['new_' filename],'w');  %# Open output file for writing
nextLine = fgets(fidInFile);                %# Get the first line of input
while nextLine >= 0                         %# Loop until getting -1 (end of file)
  nextLine = strrep(nextLine,wordA,wordB);  %# Replace wordA with wordB
  fprintf(fidOutFile,'%s',nextLine);        %# Write the line to the output file
  nextLine = fgets(fidInFile);              %# Get the next line of input
end
fclose(fidInFile);                          %# Close the input file
fclose(fidOutFile);                         %# Close the output file
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜