How to cipher an input file?

조회 수: 13 (최근 30일)
Karou
Karou 2018년 11월 14일
댓글: Karou 2018년 11월 15일
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

채택된 답변

Guillaume
Guillaume 2018년 11월 14일
편집: Guillaume 2018년 11월 14일
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)))
  댓글 수: 1
Karou
Karou 2018년 11월 15일
Thank you kindly sir, worked :D

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Encryption / Cryptography에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by