Please use MATLAB to complete this question, thx. Problem 3. (40 points) Write a
ID: 3731661 • Letter: P
Question
Please use MATLAB to complete this question, thx.
Problem 3. (40 points) Write a program that reads an arbitrary number of real values from a user-specified file, rounds the values to integers out to a user-specified output file. Make sure that the input file exists, and if not, tell the user and ask for another input file. If the output file exists, ask the user whether or not to delete it. If not, prompt for a different output file name. You can use the exist function to check the existence of a file.Explanation / Answer
Solution:
code:
% Get the name of the file containing the input data.
filename1 = input('Enter the input file name: ','s');
% Check to see that file exists
while ~exist(filename1,'file')
disp('Input file does not exist. Try again!');
filename1 = input('Enter the input file name: ','s');
end
% Get the name of the file to write the output data to.
filename2 = input('Enter the output file name: ','s');
% Check to see if output file exists
while exist(filename2,'file')
yn = input('Output file exists. Replace (Y/N)? ');
if yn(1) == 'Y' | yn(1) == 'y'
% Replace output file
break;
else
% Get new file name
filename2 = input('Enter new output file name: ','s');
end
end
% Open the input file. The file permission is 'r' because
% the file must already exist.
fid1 = fopen(filename1,'r');
% Is the open OK?
if fid1 < 0
% Open failed. Tell user.
fprintf('Open failed on input file: FID = %d ',fid1);
else
% File opened successfully. Open output file.
fid2 = fopen(filename2,'w');
% Is the open OK?
if fid2 < 0
% Open failed. Tell user.
fprintf('Open failed on output file: FID = %d ',fid2);
else
% It all ready. Get the data now.
while feof(fid1) == 0
value = fscanf(fid1,'%f',1);
fprintf(fid2,' %d ',round(value));
end
% All done. Close output file.
fclose(fid2);
end
% All done. Close input file.
fclose(fid1);
end
I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)