Lab 9: File Input/Output

File Input/Output

Today we'll practice reading from and writing to files. First, a few pointers below.

Q: How to read from a file?
A: textscan()
You must first open the file, then scan from it, then close it.
Here are some examples.

Contents of data file Sample code
2 14
3 12
5 23
 >>fid = fopen('data.txt'); 
 >>myData  =  textscan(fid,'%u %u \n');
 >>fclose(fid);
 >>myData{1}
 ans = 
            2
            3
            5
 >>myData{2}
 ans = 
            14
            12
            23
The Artist, PG-13, 21.69
The King's Speech, PG-13, 17.99
The Hurt Locker, R, 19.99
Slumdog Millionaire, R, 15.99
No Country for Old Men, R, 14.26
The Lives of Others, R, 15.76
There Will Be Blood,R, 16.99
The Bourne Ultimatum, PG-13, 8.99
Ratatouille, G, 13.99
...
>>fid = fopen('movies.txt'); 
>>movieData  =  textscan(fid,'%s %s %f2.2 \n',...
                                  'delimiter',',');
 >>fclose(fid);
>>movieData{1}
ans = 
       'The Artist'
       'The King's Speech'
       'The Hurt Locker'
       'Slumdog Millionaire'
       'No Country for Old Men'
       ...
>>movieData{2}
ans =
       'PG-13'
       'PG-13'
       'R'
       'R'
       'R'
       ...
The top selling albums of all time
Title, Artist, Release Yr, Genre, Sales (millions)
Thriller, Michael Jackson, 1982, R&B, 65
Back in Black, AC/DC, 1980, Hard Rock,42
Millennium, Backstreet Boys, 1999, Pop, 40
The Bodyguard (soundtrack), Whitney Houston/ Various artists, 1992, Pop,42

textscan graphic
>>fid = fopen('music.txt'); 
>>musicData  =  textscan(fid,'%s %s %u %s %u \n',...
                 'delimiter',',','headerlines',2);
 >>fclose(fid);

>>musicData{1}
ans =  
    'Thriller'
    'Back in Black'
    'Millennium'
    'The Bodyguard (soundtrack)'

>>musicData{2}
ans =
    'Michael Jackson'
    'AC/DC'
    'Backstreet Boys'
    'Whitney Houston/ Various artists'

>>musicData{3}
ans =
       1982
       1980
       1999
       1992

Q: How to write to a file?
A: You'll need fopen, fprintf and fclose
fid = fopen('new_file_name', 'w'); % the 'w' stands for write
fprintf(fid, 'format string for writing out values');
fclose(fid);

Q: What does the percent symbol do?
A:(short) It acts as a format template.
The basics:
string %s
fixed point %f
unsigned integer %u
A: (long) A useful reference page with more formatting information.

Useful pointers:
Alignment is possible

  • \n prints newline
  • \r prints return
  • \t prints tab
  • \b prints backspace

Your Task: Use textscan and fprintf (to read from and write to a file)

  • Try reading in the file called party.txt in your assign7_files folder.
  • Examine the format of the file first, then write your code and test it to make sure that the data is read in correctly.
  • Then write out a new file called snacks.txt that contains the list of snack foods only, like this:
    List of Sohie's snacks 
    Chips 
    Pretzels 
    Popcorn 
    Pringles 
    Doritoes 
    Cheetos 
    Oreos