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 |
|
|
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 ... |
|
|
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
|
|
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
Q: What does the percent symbol do?
fprintf(fid, 'format string for writing out values');
fclose(fid);
A:(short) It acts as a format template.
The basics:
| string | %s |
| fixed point | %f |
| unsigned integer | %u |
Useful pointers:
party.txt in your assign7_programs 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
cs112/ folder.