Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 18 File I/O Richard Gesick. File Input / Output Consider that a program may want to make its data persistent (or not rely upon the user for input)

Similar presentations


Presentation on theme: "Lecture 18 File I/O Richard Gesick. File Input / Output Consider that a program may want to make its data persistent (or not rely upon the user for input)"— Presentation transcript:

1 Lecture 18 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 14-2

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) 14-3

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 14-4

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(); 14-5

6 Reading / Writing data Reading data from the file int x = Int32.Parse(sr.ReadLine()); or while (!sr.EndOfStream) { Console.WriteLine(sr.ReadLine()); } Writing data to the file sw.WriteLine(42); 14-6

7 loading a "game world" information: 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 14-7

8 loading a "game world" information: private void LoadWorld() { // 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(); } 14-8


Download ppt "Lecture 18 File I/O Richard Gesick. File Input / Output Consider that a program may want to make its data persistent (or not rely upon the user for input)"

Similar presentations


Ads by Google