C# 0 The Complete Reference


PART I C h a p t e r   1 4



Download 4,07 Mb.
Pdf ko'rish
bet487/1096
Sana23.01.2022
Hajmi4,07 Mb.
#402171
1   ...   483   484   485   486   487   488   489   490   ...   1096
Bog'liq
C-Sharp 3 The Complete Reference Herbert Schildt


PART I

C h a p t e r   1 4 :  

U s i n g   I / O  

375


PART IPART I

    int i;

    FileStream fin;

    if(args.Length != 1) {

      Console.WriteLine("Usage: ShowFile File");

      return;

    }

    try {



      fin = new FileStream(args[0], FileMode.Open);

    } catch(IOException exc) {

      Console.WriteLine("Cannot Open File");

      Console.WriteLine(exc.Message);

      return;

    }


    // Read bytes until EOF is encountered.

    do {


      try {

        i = fin.ReadByte();

      } catch(IOException exc) {

        Console.WriteLine("Error Reading File");

        Console.WriteLine(exc.Message);

        break;

      }

      if(i != -1) Console.Write((char) i);

    } while(i != -1);

    fin.Close();

  }

}

Writing to a File



To write a byte to a file, use the 

WriteByte( )

 method. Its simplest form is shown here:

void WriteByte(byte 

val

)

This method writes the byte specified by 



val

 to the file. If the underlying stream is 

not opened for output, a 

NotSupportedException

 is thrown. If the stream is closed, 



ObjectDisposedException

 is thrown.

You can write an array of bytes to a file by calling 

Write( )

. It is shown here:

void Write(byte[ ] 

buf

, int 


offset

, int 


numBytes

)

Write( )

 writes 

numBytes

 bytes from the array 



buf,

 beginning at 



buf

[

offset

], to the file. The 

number of bytes written is returned. If an error occurs during writing, an 



IOException

 is 


thrown. If the underlying stream is not opened for output, a 

NotSupportedException

 is 


thrown. Several other exceptions are also possible.

As you may know, when file output is performed, often that output is not immediately 

written to the actual physical device. Instead, output is buffered by the operating system 

until a sizable chunk of data can be written all at once. This improves the efficiency of the 

system. For example, disk files are organized by sectors, which might be anywhere from 128 

bytes long, on up. Output is usually buffered until an entire sector can be written all at once. 

www.freepdf-books.com



376

 

P a r t   I :  



T h e   C #   L a n g u a g e

However, if you want to cause data to be written to the physical device whether the buffer 

is full or not, you can call 

Flush( )

, shown here:

void Flush( )

An

IOException

 is thrown on failure. If the stream is closed, 

ObjectDisposedException

 is 


thrown.

Once you are done with an output file, you must remember to close it using 



Close( )

.

Doing so ensures that any output remaining in a disk buffer is actually written to the disk. 



Thus, there is no reason to call 

Flush( )

 before closing a file.

Here is a simple example that writes to a file:

// Write to a file.

using System;

using System.IO;

class WriteToFile {

  static void Main(string[] args) {

    FileStream fout;

    // Open output file.

    try {

      fout = new FileStream("test.txt", FileMode.Create);

    } catch(IOException exc) {

      Console.WriteLine("Cannot Open File");

      Console.WriteLine(exc.Message);

      return;

    }

    // Write the alphabet to the file.



    try {

      for(char c = 'A'; c <= 'Z'; c++)

        fout.WriteByte((byte) c);

    } catch(IOException exc) {

      Console.WriteLine("Error Writing File");

      Console.WriteLine(exc.Message);

    }

    fout.Close();



  }

}

The program first opens a file called 



test.txt

 for output. It then writes the uppercase 

alphabet to the file. Finally, it closes the file. Notice how possible I/O errors are handled by 

the


try

/

catch

 blocks. After this program executes, 

test.txt

 will contain the following output:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Using FileStream to Copy a File

One advantage to the byte-oriented I/O used by 



FileStream

 is that you can use it on any 

type of file—not just those that contain text. For example, the following program copies 

any type of file, including executable files. The names of the source and destination files 

are specified on the command line.

www.freepdf-books.com




Download 4,07 Mb.

Do'stlaringiz bilan baham:
1   ...   483   484   485   486   487   488   489   490   ...   1096




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish