%% Download File and List Contents of Folders
% To open a connection to an FTP server, create an FTP object. Use the FTP object to download a file and list the contents of subfolders on the server. At the end of the FTP session, close the connection.
% First, connect to the National Centers for Environmental Information (NCEI) FTP server.

ftpobj = ftp('ftp.ngdc.noaa.gov')

%
% List the contents of the top-level folder.

dir(ftpobj)

%
% Download the README.txt file from the FTP server. The mget function downloads a copy to your current MATLAB® folder.
%

mget(ftpobj,'README.txt');

%
% Read the contents of your copy of README.txt using the fileread function. Split the text into lines using the splitlines function and display the first four lines.

readme = fileread('README.txt');
readme = splitlines(readme);
readme(1:4)

%
% List the contents of a subfolder using the dir function.

dir(ftpobj,'STP')

%
% Change to a subfolder using the cd function. The output from cd is the path to the current folder on the FTP server, not your current MATLAB folder.

cd(ftpobj,'STP/space-weather')

%
% List the contents of the current folder.
%

dir(ftpobj)

%
% Close the connection to the FTP server. You also can close the connection by deleting the FTP object or letting the connection time out.

close(ftpobj)

%
% FTP service courtesy of the National Centers for Environmental Information (NCEI). See the NCEI Privacy Policy, Disclaimer, and Copyright for NCEI terms of service.
% Copyright 2012 The MathWorks, Inc.