Why Does Streamreader Read 1st Line Then 1st Line Again C

3. Files

THE DATA AND PROGRAMS IN A COMPUTER'S Chief Retention survive only every bit long equally the power is on. For more permanent storage, computers use files, which are collections of information stored on a hard disk, on a floppy disk, on a CD-ROM, or on some other type of storage device. Files are organized into directories (sometimes called "folders"). A directory can hold other directories, likewise every bit files. Both directories and files have names that are used to identify them.

Fundamentally, a file is an ordered collection of bytes that has been given a name. Files can be categorized into 2 broad categories: text files and binary files. Both kinds of files contain an ordered drove of bytes, merely while binary files can contain both printable and not-printable bytes, text files are usually limited to containing printable characters.

Programs can read data from existing files. They tin create new files and can write data to files. In C#, such input and output is washed using streams. StreamReader objects read data from text files, and StreamWriter objects create and write information to text files. For files that store information in machine format, other classes are used. In this section, I will only discuss text-oriented file I/O using the StreamReader and StreamWriter classes.

3.1. Text Files

Text files comprise printable characters divided into lines. When you view a text file in a text editor such as Notepad, you can easily see where one line of text ends and the adjacent begins, because Notepad visually shows the line breaks. When the text file is saved to disk, the editor must put a special marker at the end of each line so that the line breaks are not lost. On disk, each line of text is separated past a ii-character sequence: a railroad vehicle return character followed by a newline grapheme ("\r\north"). For example, consider a file of text every bit viewed in Notepad:

Figure vii.1. A Text File

A Text File

On disk, the file would exist represented this fashion:

When Notepad loads a text file from deejay, it knows where to break the lines, because the \r\n sequence indicates the end of each line.

iii.two. Reading Files

To write a C# programme that reads a text file, you utilize the StreamReader form. Information technology has a constructor which takes the proper noun of a file as a parameter and creates an input stream that can be used for reading from that file. For example, to create an input stream to read from a file named "data.txt", you lot could write:

StreamReader rd = new StreamReader("information.txt");

Once y'all take created the input stream object (rd in this instance), y'all tin do two things with it:

  • Read data from the file (using the Read() and ReadLine() methods)

  • Close the file (using the Close() method) when you're finished reading data from information technology

The Read() method returns the next character from the file, merely it returns it as an int, not a char:

int nextChar = rd.Read();

Each time you call Read(), the next graphic symbol is returned. When y'all've read all the characters in the file, -1 is returned (that explains why Read() returns an int; it has to be able to render something that indicates that the cease of file has been reached).

Here'southward a program that reads all the information from a text file and displays information technology on the screen:

Example 7.i. ShowFile.cs

using System; using System.IO;  class ShowFile {    static void Main() {       StreamReader file = new StreamReader("data.txt");       int ch = file.Read();       while (ch != -ane) {         Console.Write((char)ch);         ch = file.Read();       }       file.Shut();   } }

Detect the statement

using Organisation.IO;

at the height of the plan. The StreamReader class, dissimilar all of the other classes we have used to this point, is non in the System namespace. It is in the Arrangement.IO namespace. The using System.IO statement allows us to apply the StreamReader class.

StreamReaders likewise let y'all to read data using the ReadLine() method. The ReadLine() method reads the side by side line of information from the text file and returns it. Eventually, ReadLine() will return the terminal line in the file, and subsequent calls will return a null value. I will accept more to say well-nigh naught values in the next chapter, merely for now, you lot should know how to test for cipher. Do it using == or !=, like this:

if (line == null) {   // we hit the stop of file }

I want to emphasize that nada is non a cord value. Instead, it is a special value indicating that the variable does non hold a cord. Information technology is different from an empty cord. You have to be careful non to telephone call any methods or access backdrop on a string variable when it holds a null value, considering that will result in a NullReferenceException. That's why y'all shouldn't exam for zilch like this:

// THIS Tin CAUSE A CRASH if (line.Length == 0) { ... }

If line is null, and then calling the equals method will cause a crash. When you exam for zilch, always use the relational operators.

Here's a plan that displays the contents of a text file using the ReadLine() method.

Example 7.2. ShowFile2.cs

using System; using System.IO;  class ShowFile2 {    static void Main() {      try {       StreamReader file = new StreamReader("data.txt");        string line = file.ReadLine();       while (line != null) {         Console.WriteLine(line);         line = file.ReadLine();       }       file.Close( );      } take hold of (IOException e) {       Console.WriteLine("Uh oh! Problem reading the file: " + due east.Message);     }    } }

Notice particularly the while loop condition:

line != zero

This condition is true until the end of file is reached.

As well, note the employ of a endeavor-catch cake to gracefully handle exceptions that may occur, such every bit file not found, or problems reading data from the disk.

three.3. Writing Files

Writing data to files is much similar reading data. Yous simply create an object belonging to the class StreamWriter. For case, suppose you want to write information to a file named "event.txt". Y'all might use code like the post-obit:

            StreamWriter result = new StreamWriter("event.txt");       upshot.WriteLine("Here is the first line");       consequence.WriteLine("Here is the 2d line");       result.Shut();          

If no file named result.txt exists, a new file will be created. If the file already exists, so the current contents of the file will exist erased and replaced with the data that your program writes to the file. An IOException might occur if, for example, you are trying to create a file on a disk that is "write-protected," meaning that it cannot be modified.

After you lot are finished using a file, information technology'southward a good idea to shut the file, to tell the operating system that yous are finished using information technology. (If you forget to do this, the file volition ordinarily be closed automatically when the plan terminates or when the file stream object is garbage collected, but it's best to close a file every bit soon as y'all are washed with it.) Y'all tin can close a file by calling the Close() method of the associated stream. Once a file has been airtight, it is no longer possible to read data from it or write data to it, unless you open it once again every bit a new stream.

hopkinswintelpom.blogspot.com

Source: https://protect.bju.edu/cps/docs/cps110/textbook/ch07s03.html

0 Response to "Why Does Streamreader Read 1st Line Then 1st Line Again C"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel