C #. net-da matnli fayllar bilan ishlash


Appending text to an existing file



Download 88,34 Kb.
bet2/2
Sana11.01.2020
Hajmi88,34 Kb.
#33215
1   2
Bog'liq
C

Appending text to an existing file


If the file doesn't exist, the code above will create it. If it does exist, it will be overwritten. This behavior can be altered by specifying the second parameter in the StreamWriter's constructor. If we set it to true, it'll append text rather than overwrite it. We add a new line to an existing file like this:

using (StreamWriter sw = new StreamWriter(@"file.txt", true))

{

sw.WriteLine("The appended line");



sw.Flush();

}

Another parameter that may be passed is the encoding, but UTF-8 is default, which should suit us in most cases.


Reading an existing file


The only thing left for us to learn is how to read a file. It isn't any more complicated than writing. As usual, there is a .NET framework class for it - StreamReader. It works pretty much like StreamWriter, but instead of the WriteLine() method we use ReadLine() which returns a line of text from the file and moves to the next line. With this in mind, we'll call it in a while loop. The condition to avoid reading beyond the file may seem a little tricky, however, all we're doing is checking whether the line has been assigned to the variable.

The code to print the file contents to the console would look like this:



using (StreamReader sr = new StreamReader(@"file.txt"))

{

string s;



while ((s = sr.ReadLine()) != null)

{

Console.WriteLine(s);



}

}

The code for our entire application now looks similar to this:



// writing to the file

using (StreamWriter sw = new StreamWriter(@"file.txt"))

{

sw.WriteLine("The first line");



sw.WriteLine("This text is on the second line");

sw.WriteLine("And the third one.");

sw.Flush();

}

Console.WriteLine("The file has been successfully written.");


// appending a text to the file

using (StreamWriter sw = new StreamWriter(@"file.txt", true))

{

sw.WriteLine("An appended line");



sw.Flush();

}

Console.WriteLine("A new line has been successfully appended into the file.");


// printing the contents of the file

Console.WriteLine("Printing file contents:");


using (StreamReader sr = new StreamReader(@"file.txt"))

{

string s;



while ((s = sr.ReadLine()) != null)

{

Console.WriteLine(s);



}

}

Console.ReadKey();



The result:

Console applicationThe file has been successfully written.

A new line has been successfully appended into the file.

Printing file contents:

The first line

This text is on the second line

And the third one.

An appended line


The File class


The .NET framework contains the static File class with pre-made methods that don't fully replace the StreamReader/Stre­amWriter classes, but we might get by without them in most cases. The last example, which prints all of the lines in a file could be written as follows (don't forget to add using System.IO):

string[] lines = File.ReadAllLines(@"file.txt");

foreach (string line in lines)

{

Console.WriteLine(line);



}

The ReadAllLines() method returns all of the lines in a text file as an array of strings. If the file isn't too large, this method is much easier to use. There are other similar methods in the File class such as WriteAllLines(a­rrayOfStrings, pathToFile) or AppendAllLines(a­rrayOfStrings, pathToFile). The first one writes lines from a string array into a file, the other appends lines from a string array to an existing file. The class also includes methods that don't work with lines, but with continuous text. These are WriteAllText(text), ReadAllText(), and AppendAllText(tex­t).

In this article, we've omitted exception handling and writing privileges. Next time, we'll look into storing objects into files.

The Basics of C Programming




 



 



 



BY MARSHALL BRAIN & CHRIS POLLETTE

Binary Files


  PREV UP NEXT  

Binary files are very similar to arrays of structures, except the structures are in a disk file rather than in an array in memory. Because the structures in a binary file are on disk, you can create very large collections of them (limited only by your available disk space). They are also permanent and always available. The only disadvantage is the slowness that comes from disk access time.

Binary files have two features that distinguish them from text files:


  • You can jump instantly to any structure in the file, which provides random access as in an array.

  • You can change the contents of a structure anywhere in the file at any time.

Binary files also usually have faster read and write times than text files, because a binary image of the record is stored directly from memory to disk (or vice versa). In a text file, everything has to be converted back and forth to text, and this takes time.

C supports the file-of-structures concept very cleanly. Once you open the file you can read a structure, write a structure, or seek to any structure in the file. This file concept supports the concept of a file pointer. When the file is opened, the pointer points to record 0 (the first record in the file). Any read operation reads the currently pointed-to structure and moves the pointer down one structure. Any write operation writes to the currently pointed-to structure and moves the pointer down one structure. Seek moves the pointer to the requested record.

Keep in mind that C thinks of everything in the disk file as blocks of bytes read from disk into memory or read from memory onto disk. C uses a file pointer, but it can point to any byte location in the file. You therefore have to keep track of things.

The following program illustrates these concepts:

#include
/* random record description - could be anything */

struct rec

{

int x,y,z;



};
/* writes and then reads 10 arbitrary records

from the file "junk". */

int main()

{

int i,j;



FILE *f;

struct rec r;


/* create the file of 10 records */

f=fopen("junk","w");

if (!f)

return 1;



for (i=1;i<=10; i++)

{

r.x=i;



fwrite(&r,sizeof(struct rec),1,f);

}

fclose(f);


/* read the 10 records */

f=fopen("junk","r");

if (!f)

return 1;



for (i=1;i<=10; i++)

{

fread(&r,sizeof(struct rec),1,f);



printf("%d\n",r.x);

}

fclose(f);



printf("\n");
/* use fseek to read the 10 records

in reverse order */

f=fopen("junk","r");

if (!f)


return 1;

for (i=9; i>=0; i--)

{

fseek(f,sizeof(struct rec)*i,SEEK_SET);



fread(&r,sizeof(struct rec),1,f);

printf("%d\n",r.x);

}

fclose(f);



printf("\n");
/* use fseek to read every other record */

f=fopen("junk","r");

if (!f)

return 1;



fseek(f,0,SEEK_SET);

for (i=0;i<5; i++)

{

fread(&r,sizeof(struct rec),1,f);



printf("%d\n",r.x);

fseek(f,sizeof(struct rec),SEEK_CUR);

}

fclose(f);



printf("\n");
/* use fseek to read 4th record,

change it, and write it back */

f=fopen("junk","r+");

if (!f)


return 1;

fseek(f,sizeof(struct rec)*3,SEEK_SET);

fread(&r,sizeof(struct rec),1,f);

r.x=100;


fseek(f,sizeof(struct rec)*3,SEEK_SET);

fwrite(&r,sizeof(struct rec),1,f);

fclose(f);

printf("\n");


/* read the 10 records to insure

4th record was changed */

f=fopen("junk","r");

if (!f)


return 1;

for (i=1;i<=10; i++)

{

fread(&r,sizeof(struct rec),1,f);



printf("%d\n",r.x);

}

fclose(f);



return 0;

}

In this program, a structure description rec has been used, but you can use any structure description you want. You can see that fopen and fclose work exactly as they did for text files.



The new functions here are freadfwrite and fseek. The fread function takes four parameters:

  • A memory address

  • The number of bytes to read per block

  • The number of blocks to read

  • The file variable

Thus, the line fread(&r,sizeof(struct rec),1,f); says to read 12 bytes (the size of rec) from the file f (from the current location of the file pointer) into memory address &r. One block of 12 bytes is requested. It would be just as easy to read 100 blocks from disk into an array in memory by changing 1 to 100.

The fwrite function works the same way, but moves the block of bytes from memory to the file. The fseek function moves the file pointer to a byte in the file. Generally, you move the pointer in sizeof(struct rec) increments to keep the pointer at record boundaries. You can use three options when seeking:



  • SEEK_SET

  • SEEK_CUR

  • SEEK_END

SEEK_SET moves the pointer x bytes down from the beginning of the file (from byte 0 in the file). SEEK_CUR moves the pointer x bytes down from the current pointer position. SEEK_END moves the pointer from the end of the file (so you must use negative offsets with this option).

Several different options appear in the code above. In particular, note the section where the file is opened with r+ mode. This opens the file for reading and writing, which allows records to be changed. The code seeks to a record, reads it, and changes a field; it then seeks back because the read displaced the pointer, and writes the change back.

For more information on C and related topics, check out the links below.

Reading and Writing from Binary Files


Binary files are very similar to arrays except for the fact that arrays are temporary storage in the memory but binary files are permanent storage in the disks. The most important difference between binary files and a text file is that in a binary file, you can seekwrite, or read from any position inside the file and insert structures directly into the files. You must be wondering - why do we need binary files when we already know how to handle plaintexts and text files? Here are the reasons why binary files are necessary:

1. I/O operations are much faster with binary data.


Usually, large text files contain millions of numbers. It takes a lot of time to convert 32-bit integers to readable characters. This conversion is not required in the case of binary files as data can be directly stored in the form of bits.

2. Binary files are much smaller in size than text files.


For data that is in the form of images, audio or video, this is very important. Small size means less storage space and faster transmission. For example, a storage device can store a large amount of binary data as compared to data in character format.

3. Some data cannot be converted to character formats.


For example, Java compilers generate bytecodes after compilation.

Having said that, let's move on to handling I/O operations in a binary file in C. The basic parameters that the read and write functions of binary files accept are:



  • the memory address of the value to be written or read

  • the number of bytes to read per block

  • the total number of blocks to read

  • the file pointer

There are functions provided by C libraries to seekread, and write to binary files. Let's explain this by reading and writing a structure called rec in a binary file. The structure is defined like this:


  1. /* The structure to be inserted in the binary file */

  2. struct record



  3.  int a,b,c;

  4. };

The fread() function is used to read a specific number of bytes from the file. An example of fread() looks like this:




  1. fread(&myRecord, sizeof(struct record), 1, ptr);

This statement reads 'a' bytes (in this case, it's the size of the structure) from the file into the memory address &myRecord. Here the number 1 denotes the number of blocks of 'a' bytes to be read. If we change it to 10, then it denotes 10 blocks of 'a' bytes will be read and stored into &myRecordptr is the pointer to the location of the file that is being read.

Now the fwrite() function is used to write to a binary file, like so:


  1. fwrite(&myRecord, sizeof(struct record), 1, ptr);

In this example, the value inside the address &myRecord which is of the size of the structure record is written into the file with the help of the file pointer ptr.


Examples using fread() & frwrite()


Now that you know how to read and write binary files, let's discuss this with the help of examples, starting with an example of using fread().


  1. #include

  2. /* Our structure */

  3. struct record



  4.   int a,b,c;

  5. };

  6. int main()



  7.  int count;

  8.  FILE *ptr;

  9.  struct record myRecord;

  10.  ptr=fopen("test.bin","rb");

  11.  if (!ptr)

  1.  { printf("Unable to open file!");     return 1;

  2.  }

  3.  for ( count=1; count <= 10; count++)

  4.  { 

  5.   fread(&myRecord,sizeof(struct record),1,ptr);   printf("%d\n",myRecord.a);

  6.  }  fclose(ptr);

  1. Return 0:}


Why files are needed?


  • When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program terminates.

  • If you have to enter a large number of data, it will take a lot of time to enter them all.
    However, if you have a file containing all the data, you can easily access the contents of the file using a few commands in C.

  • You can easily move your data from one computer to another without any changes.


Types of Files


When dealing with files, there are two types of files you should know about:

  1. Text files

  2. Binary files

1. Text files


Text files are the normal .txt files. You can easily create text files using any simple text editors such as Notepad.

When you open those files, you'll see all the contents within the file as plain text. You can easily edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide the least security and takes bigger storage space.

2. Binary files


Binary files are mostly the .bin files in your computer.

Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold a higher amount of data, are not readable easily, and provides better security than text files.


File Operations


In C, you can perform four major operations on files, either text or binary:

  1. Creating a new file

  2. Opening an existing file

  3. Closing a file

  4. Reading from and writing information to a file


Working with files


When working with files, you need to declare a pointer of type file. This declaration is needed for communication between the file and the program.

  1. FILE *fptr;


Opening a file - for creation and edit


Opening a file is performed using the fopen() function defined in the stdio.h header file.

The syntax for opening a file in standard I/O is:



  1. ptr = fopen("fileopen","mode");

For example,

  1. fopen("E:\\cprogram\\newprogram.txt","w");



  2. fopen("E:\\cprogram\\oldprogram.bin","rb");

  • Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The first function creates a new file named newprogram.txt and opens it for writing as per the mode 'w'.
    The writing mode allows you to create and edit (overwrite) the contents of the file.

  • Now let's suppose the second binary file oldprogram.bin exists in the location E:\cprogram. The second function opens the existing file for reading in binary mode 'rb'.
    The reading mode only allows you to read the file, you cannot write into the file.

Mode

Meaning of Mode

During Inexistence of file

r

Open for reading.

If the file does not exist, fopen() returns NULL.

rb

Open for reading in binary mode.

If the file does not exist, fopen() returns NULL.

w

Open for writing.

If the file exists, its contents are overwritten.
If the file does not exist, it will be created.

wb

Open for writing in binary mode.

If the file exists, its contents are overwritten.
If the file does not exist, it will be created.

a

Open for append.
Data is added to the end of the file.

If the file does not exist, it will be created.

ab

Open for append in binary mode.
Data is added to the end of the file.

If the file does not exist, it will be created.

r+

Open for both reading and writing.

If the file does not exist, fopen() returns NULL.

rb+

Open for both reading and writing in binary mode.

If the file does not exist, fopen() returns NULL.

w+

Open for both reading and writing.

If the file exists, its contents are overwritten.
If the file does not exist, it will be created.

wb+

Open for both reading and writing in binary mode.

If the file exists, its contents are overwritten.
If the file does not exist, it will be created.

a+

Open for both reading and appending.

If the file does not exist, it will be created.

ab+

Open for both reading and appending in binary mode.

If the file does not exist, it will be created.

Opening Modes in Standard I/O


Closing a File


The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using the fclose() function.



  1. fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.


Reading and writing to a text file


For reading and writing to a text file, we use the functions fprintf() and fscanf().

They are just the file versions of printf() and scanf(). The only difference is that fprint() and fscanf() expects a pointer to the structure FILE.




Example 1: Write to a text file


  1. #include

  2. #include



  3. int main()

  4. {

  5. int num;

  6. FILE *fptr;



  7. // use appropriate location if you are using MacOS or Linux

  8. fptr = fopen("C:\\program.txt","w");



  9. if(fptr == NULL)

  10. {

  11. printf("Error!");

  12. exit(1);

  13. }



  14. printf("Enter num: ");

  15. scanf("%d",&num);



  16. fprintf(fptr,"%d",num);

  17. fclose(fptr);



  18. return 0;

  19. }

This program takes a number from the user and stores in the file program.txt.

After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open the file, you can see the integer you entered.




Example 2: Read from a text file


  1. #include

  2. #include



  3. int main()

  4. {

  5. int num;

  6. FILE *fptr;



  7. if ((fptr = fopen("C:\\program.txt","r")) == NULL){

  8. printf("Error! opening file");



  9. // Program exits if the file pointer returns NULL.

  10. exit(1);

  11. }



  12. fscanf(fptr,"%d", &num);



  13. printf("Value of n=%d", num);

  14. fclose(fptr);



  15. return 0;

  16. }

This program reads the integer present in the program.txt file and prints it onto the screen.

If you successfully created the file from Example 1, running this program will get you the integer you entered.



Other functions like fgetchar()fputc() etc. can be used in a similar way.


Reading and writing to a binary file


Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files.


Writing to a binary file


To write into a binary file, you need to use the fwrite() function. The functions take four arguments:

  1. address of data to be written in the disk

  2. size of data to be written in the disk

  3. number of such type of data

  4. pointer to the file where you want to write.

  1. fwrite(addressData, sizeData, numbersData, pointerToFile);


Example 3: Write to a binary file using fwrite()


  1. #include

  2. #include



  3. struct threeNum

  4. {

  5. int n1, n2, n3;

  6. };



  7. int main()

  8. {

  9. int n;

  10. struct threeNum num;

  11. FILE *fptr;



  12. if ((fptr = fopen("C:\\program.bin","wb")) == NULL){

  13. printf("Error! opening file");



  14. // Program exits if the file pointer returns NULL.

  15. exit(1);

  16. }



  17. for(n = 1; n < 5; ++n)

  18. {

  19. num.n1 = n;

  20. num.n2 = 5*n;

  21. num.n3 = 5*n + 1;

  22. fwrite(&num, sizeof(struct threeNum), 1, fptr);

  23. }

  24. fclose(fptr);



  25. return 0;

  26. }

In this program, we create a new file program.bin in the C drive.

We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the main function as num.

Now, inside the for loop, we store the value into the file using fwrite().

The first parameter takes the address of num and the second parameter takes the size of the structure threeNum.

Since we're only inserting one instance of num, the third parameter is 1. And, the last parameter *fptr points to the file we're storing the data.

Finally, we close the file.




Reading from a binary file


Function fread() also take 4 arguments similar to the fwrite() function as above.

  1. fread(addressData, sizeData, numbersData, pointerToFile);


Example 4: Read from a binary file using fread()


  1. #include

  2. #include



  3. struct threeNum

  4. {

  5. int n1, n2, n3;

  6. };



  7. int main()

  8. {

  9. int n;

  10. struct threeNum num;

  11. FILE *fptr;



  12. if ((fptr = fopen("C:\\program.bin","rb")) == NULL){

  13. printf("Error! opening file");



  14. // Program exits if the file pointer returns NULL.

  15. exit(1);

  16. }



  17. for(n = 1; n < 5; ++n)

  18. {

  19. fread(&num, sizeof(struct threeNum), 1, fptr);

  20. printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);

  21. }

  22. fclose(fptr);



  23. return 0;

  24. }

In this program, you read the same file program.bin and loop through the records one by one.

In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr into the structure num.

You'll get the same records you inserted in Example 3.


Getting data using fseek()


If you have many records inside a file and need to access a record at a specific position, you need to loop through all the records before it to get the record.

This will waste a lot of memory and operation time. An easier way to get to the required data can be achieved using fseek().



As the name suggests, fseek() seeks the cursor to the given record in the file.


Syntax of fseek()


  1. fseek(FILE * stream, long int offset, int whence);

The first parameter stream is the pointer to the file. The second parameter is the position of the record to be found, and the third parameter specifies the location where the offset starts.

Whence

Meaning

SEEK_SET

Starts the offset from the beginning of the file.

SEEK_END

Starts the offset from the end of the file.

SEEK_CUR

Starts the offset from the current location of the cursor in the file.

Different whence in fseek()


Example 5: fseek()


  1. #include

  2. #include



  3. struct threeNum

  4. {

  5. int n1, n2, n3;

  6. };



  7. int main()

  8. {

  9. int n;

  10. struct threeNum num;

  11. FILE *fptr;



  12. if ((fptr = fopen("C:\\program.bin","rb")) == NULL){

  13. printf("Error! opening file");



  14. // Program exits if the file pointer returns NULL.

  15. exit(1);

  16. }



  17. // Moves the cursor to the end of the file

  18. fseek(fptr, -sizeof(struct threeNum), SEEK_END);



  19. for(n = 1; n < 5; ++n)

  20. {

  21. fread(&num, sizeof(struct threeNum), 1, fptr);

  22. printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);

  23. fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);

  24. }

  25. fclose(fptr);



  26. return 0;

  27. }

This program will start reading the records from the file program.bin in the reverse order (last to first) and prints it.
Download 88,34 Kb.

Do'stlaringiz bilan baham:
1   2




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