MATLAB: How to cipher an input file

cipherfileinputinput fileMATLAB

Hi,
I'm woring on a program that ciphers files (Caesar cipher). The program works when an user inputs a sentence, but protests when somebody is trying to do the same with a file, any idea what am I doing wrong?
clear all
fid = input('Podaj tekst:','s')
if exist(fid, 'file')%File exists
Alfabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o','p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'W','V', 'X', 'Y', 'Z' ];
i = 1;
key = input('Podaj skok:'); %Jump
plik = dlmread(fid)% Tried plik = fopen(fid) and plik = importdata(fid) as well, but those don't work either.
while key > 26
key = mod(key,26);
end
while i <= length(plik);
if isletter(plik(i)) == 1
y = strfind(Alfabet,plik(i));
z = y+key;
if z > 26
z = z - 26;
end
Szyfr(i) = Alfabet(z);
elseif isletter(plik(i)) == 0
if plik(i) == ' '
Szyfr(i)=plik(i);
end
if plik(i) == '.'
Szyfr(i) = plik(i);
end
if plik(i) == ','
Szyfr(i) = plik(i);
end
if plik(i) == ':'
Szyfr(i) = plik(i);
end
end
i = i+1;
end
dlmwrite('Cezar.txt',Szyfr,'\n')
dlmwrite('Skok.txt',key,'\n')
else
fprintf('Podany plik nie istnieje:\n%s', plik); %File doesn't exist
end

Best Answer

dlmread is not for reading text files.The easiest way to import a text file is with fileread.
plik = fileread(fid); %note that using fid as a variable name for a filename is very misleading
Similarly, dlmwrite is not for writing text files. There's no one-line equivalent to fileread unfortunately:
filename = input('name of file to write', 's');
fid = fopen(filename, 'wt');
fprintf(fid, 'Cezar: %s\n', Szyfr);
fprintf(fid, 'Skok %s\n', key);
fclose(fid);
WIth regards to your code:
while key > 26
key = mod(key,26);
end
is a pointless loop. If key is greater than 26, the mod guarantees that it will be less than 26 after that regardless of how big it is. If it is less than 26, then the mod wouldn't change it, so the whole lot is simply:
key = mod(key, 26); %no loop needed
I note that later on in your code, you seem to have forgotten about mod.
Finally, I'll leave you with this code:
plain = 'the quick brown fox jumps over the lazy fox!' %demo text
key = mod(input('Podaj skok:'), 26);
cypher('a':'z') = circshift('a':'z', -key);
encoded = plain;
encoded(isletter(plain)) = cypher(plain(isletter(plain)))
Related Question