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
|
|
The Artist, PG-13, 21.69
|
|
The top selling albums of all time
|
|
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:
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