How to Read From Binary File and Display in C

C File I/O and Binary File I/O


Past Alex Allain

In this tutorial, yous'll learn how to practice file IO, text and binary, in C, using fopen, fwrite, and fread, fprintf, fscanf, fgetc and fputc.

FILE *

For C File I/O you need to utilize a FILE arrow, which will let the programme proceed rails of the file being accessed. (You tin think of it as the memory address of the file or the location of the file).

For example:

FILE *fp;

fopen

To open a file y'all demand to use the fopen part, which returns a FILE arrow. Once you've opened a file, y'all tin use the FILE pointer to let the compiler perform input and output functions on the file.

FILE *fopen(const char *filename, const char *mode);

In the filename, if you use a cord literal every bit the statement, you lot demand to remember to use double backslashes rather than a single backslash as yous otherwise risk an escape graphic symbol such as \t. Using double backslashes \\ escapes the \ key, and then the string works as it is expected. Your users, of course, exercise non need to do this! Information technology'southward just the way quoted strings are handled in C and C++.

fopen modes

The allowed modes for fopen are as follows:

r  - open for reading w  - open for writing (file need not exist) a  - open up for appending (file demand non exist) r+ - open for reading and writing, start at beginning due west+ - open for reading and writing (overwrite file) a+ - open for reading and writing (suspend if file exists)

Annotation that information technology's possible for fopen to fail even if your plan is perfectly right: you might try to open a file specified by the user, and that file might not be (or it might be write-protected). In those cases, fopen will return 0, the Goose egg pointer.

Hither's a simple example of using fopen:

FILE *fp; fp=fopen("c:\\exam.txt", "r");

This code will open examination.txt for reading in text mode. To open a file in a binary style you lot must add a b to the cease of the mode cord; for case, "rb" (for the reading and writing modes, you can add the b either later on the plus sign - "r+b" - or before - "rb+")

fclose

When you lot're done working with a file, you should shut it using the function

int fclose(FILE *a_file);

fclose returns zero if the file is airtight successfully.

An example of fclose is

fclose(fp);

Reading and writing with fprintf, fscanf fputc, and fgetc

To work with text input and output, you lot use fprintf and fscanf, both of which are like to their friends printf and scanf except that yous must pass the FILE pointer equally starting time statement. For example:

FILE *fp; fp=fopen("c:\\test.txt", "w"); fprintf(fp, "Testing...\n");

It is too possible to read (or write) a single character at a time--this can be useful if you wish to perform character-by-character input (for example, if y'all need to continue track of every piece of punctuation in a file it would brand more sense to read in a single grapheme than to read in a string at a time.) The fgetc part, which takes a file pointer, and returns an int, will let yous read a single character from a file:

int fgetc (FILE *fp);        

Observe that fgetc returns an int. What this actually means is that when it reads a normal character in the file, it will return a value suitable for storing in an unsigned char (basically, a number in the range 0 to 255). On the other hand, when you lot're at the very end of the file, you lot tin't get a character value--in this case, fgetc volition return "EOF", which is a abiding that indicates that you lot've reached the cease of the file. To see a full example using fgetc in practice, take a look at the example here.

The fputc function allows you to write a character at a fourth dimension--you lot might find this useful if you wanted to copy a file character by grapheme. It looks similar this:

int fputc( int c, FILE *fp );        

Note that the starting time argument should exist in the range of an unsigned char so that it is a valid graphic symbol. The second argument is the file to write to. On success, fputc will render the value c, and on failure, information technology will render EOF.

Binary file I/O - fread and fwrite

For binary File I/O yous use fread and fwrite.

The declarations for each are like:

size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);                size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

Both of these functions deal with blocks of memories - commonly arrays. Because they accept pointers, you can as well use these functions with other information structures; you can fifty-fifty write structs to a file or a read struct into retentiveness.

Allow'south look at ane role to run across how the notation works.

fread takes iv arguments. Don't be confused by the declaration of a void *ptr; void ways that it is a pointer that can be used for any type variable. The beginning argument is the name of the array or the address of the structure you want to write to the file. The second argument is the size of each chemical element of the array; information technology is in bytes. For instance, if you have an assortment of characters, you would want to read it in i byte chunks, and then size_of_elements is one. You tin utilize the sizeof operator to get the size of the various datatypes; for case, if you have a variable int x; y'all can become the size of 10 with sizeof(x);. This usage works fifty-fifty for structs or arrays. E.1000., if you accept a variable of a struct type with the name a_struct, you lot tin can utilise sizeof(a_struct) to detect out how much memory it is taking up.

e.g.,

sizeof(int);

The third argument is simply how many elements you lot want to read or write; for example, if yous pass a 100 element array, you want to read no more than than 100 elements, so you pass in 100.

The final argument is simply the file pointer we've been using. When fread is used, after beingness passed an assortment, fread will read from the file until it has filled the array, and it will return the number of elements really read. If the file, for example, is only 30 bytes, but you attempt to read 100 bytes, it will return that it read 30 bytes. To check to ensure the end of file was reached, employ the feof function, which accepts a FILE arrow and returns true if the terminate of the file has been reached.

fwrite is similar in usage, except instead of reading into the memory you write from retention into a file.

For example,

FILE *fp; fp=fopen("c:\\examination.bin", "wb"); char x[10]="ABCDEFGHIJ"; fwrite(x, sizeof(x[0]), sizeof(ten)/sizeof(x[0]), fp);

Quiz yourself
Previous: Strings
Next: Typecasting
Dorsum to C Tutorial Index

Related articles

More on working with files in C

C++ file IO

grahamgaince.blogspot.com

Source: https://www.cprogramming.com/tutorial/cfileio.html

0 Response to "How to Read From Binary File and Display in C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel