I/O string

1 vue (au cours des 30 derniers jours)
Hanna Dulay
Hanna Dulay le 3 Déc 2019
Commenté : Walter Roberson le 3 Déc 2019
I'm having a difficulty on replacing the tag with the given replacement word on the given text file for the 3rd subfunction.
here is what I have done so far
function [] = ()
clc;clear
readstring = read_form('form.txt');
[tag,replacement] = read_sub_tag();
newstring = replace_tags(readstring,tag,replacement);
create_output('Tongue_Twister.txt',newstring)
end
function readstring = read_form(textfile)
readstring = []; %empty readstring
text=fopen(textfile,'r');
if text==-1 %Check if the file opened correctly
sprintf('File not correctly open')
else
while ~ feof(text) %to read until the end
txt=fgets(text); %read every single line
readstring=sprintf('%s\r',readstring,txt);
readstring=strcat(readstring);%concatenate the lines into string
end
end
fclose(text);
return
end
function [tag,replacement] = read_sub_tag()
tag = []; %empty tag
replacement = []; %empty replacement
sub_tag=fopen('sub.txt','r');
if sub_tag==-1 %check if the file opened correctly
sprintf('File not correctly opened')
else
while feof(sub_tag)==0
sub=fgetl(sub_tag);
[tag,replacement]=strtok(sub); %to create separate arrays for the tag and replacement
tag=lower(tag);
replacement=strtrim(replacement);
end
end
fclose(sub_tag);
return
end
function newstring = replace_tags(readstring,tag,replacement)
newstring = "";
r_s=lower(readstring);
i= strfind(r_s,tag);
tg=i+length(tag);
splitlines(readstring);
for final=readstring(i:tg)
newstring=replace(readstring,final,replacement);
end
return
end
function create_output('Tongue_Twister.txt';newstring)
name=fopen('Tongue_Twister.txt,''wt');
fprintf(name,newstring);
fclose(name);
end
  1 commentaire
Walter Roberson
Walter Roberson le 3 Déc 2019
while feof(sub_tag)==0
sub=fgetl(sub_tag);
[tag,replacement]=strtok(sub); %to create separate arrays for the tag and replacement
tag=lower(tag);
replacement=strtrim(replacement);
end
That code is throwing away all of the tags and replacement information, except for the very last one. Even then, in some circumstances you throw away the last one as well, as feof() is not guaranteed to be true when you have just positioned after the last newline in the file; in traditional POSIX file semantics, feof() would not be true in that situation, leading to an empty fget() result.

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by