Lab 9: File Input/Output
File Input/OutputToday we'll practice reading from and writing to files. First, a few pointers below.
Q: How to read from a file?
You must first open the file, then scan from it, then close it.
Here are some examples.
|Contents of data file||Sample code|
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');
A:(short) It acts as a format template.
- 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
- 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 Stella's snacks Chips Pretzels Popcorn Pringles Doritoes Cheetos Oreos