Download presentation
Presentation is loading. Please wait.
1
Lecture 16 File I/O Richard Gesick
2
File Input / Output Consider that a program may want to make its data persistent (or not rely upon the user for input) Reading from and writing to a file is conceptually the same as reading/writing to the console
3
Streams Streams hold data
Input streams provide data to the program (keyboard and ReadLine) The program places data onto output streams (console and WriteLine)
4
Process: Open the file stream
(many "modes" - read, write, append, create, etc.) Do what you need to do (read/write) Close the file stream (freeing it for use by other programs) You can imagine that there is an "active cursor" that is moved around the file as you read/write
5
Opening / Closing Files
Opening the file StreamReader sr = new StreamReader("data.txt"); StreamWriter sw = new StreamWriter("output.txt"); Closing the file sr.Close(); sw.Close();
6
Reading data Reading data from the file
int x = Int32.Parse(sr.ReadLine()); or string data = sr.ReadLine(); while (data != null) { string[] info = data.Split(' '); . . . data= sr.ReadLIne(); }
7
loading data from a file with varied formatting:
private void LoadWorld() { StreamReader sr = new StreamReader("world.txt"); world_width = Int32.Parse(sr.ReadLine()); world_height = Int32.Parse(sr.ReadLine()); show_width = Int32.Parse(sr.ReadLine()); show_height = Int32.Parse(sr.ReadLine()); world_background= new int[world_width, world_height]; //more on next slide
8
loading a "game world" information:
// continued from previous… string row; char[] delims = { ',' }; string[] tokens; for (int r = 0; r < world_height; r++) { row = sr.ReadLine(); tokens = row.Split(delims); for (int c = 0; c < world_width; c++) { world_background[c, r] = Int32.Parse(tokens[c]); } } sr.Close(); }
9
Writing to files StreamWriter, if the file doesn’t exist, it will create that file and opens the file for output. Many options. default: opens the file, deletes existing data StreamWriter sw = new StreamWriter("outfile.txt"); Opens the file, appends data to existing data StreamWriter sw = new StreamWriter("outfile.txt",true);
10
Writing data Writing data to the file Or
sw.WriteLine(42); Or sw.WriteLine(lname + " " + fname + " " + avg); Or if the object has a to string that will provide the necessary information: foreach ( Person p in personList) sw.WriteLine(p);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.