Read Double Word From Binary File C++

C File I/O and Binary File I/O


By Alex Allain

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

FILE *

For C File I/O y'all demand to apply a FILE pointer, which will let the program keep track of the file being accessed. (You lot tin can think of it as the memory address of the file or the location of the file).

For case:

FILE *fp;

fopen

To open a file you need to use the fopen role, which returns a FILE pointer. Once yous've opened a file, you tin utilize the FILE arrow to let the compiler perform input and output functions on the file.

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

In the filename, if y'all use a string literal as the argument, you lot need to remember to utilize double backslashes rather than a unmarried backslash as you lot otherwise risk an escape character such as \t. Using double backslashes \\ escapes the \ key, and so the string works as it is expected. Your users, of course, do non need to exercise this! It's just the manner quoted strings are handled in C and C++.

fopen modes

The allowed modes for fopen are as follows:

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

Notation that it'due south possible for fopen to fail even if your program is perfectly correct: you might endeavor to open a file specified by the user, and that file might not exist (or it might be write-protected). In those cases, fopen will return 0, the Zippo pointer.

Here's a simple example of using fopen:

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

This code volition open up exam.txt for reading in text mode. To open a file in a binary mode you must add a b to the cease of the manner cord; for instance, "rb" (for the reading and writing modes, yous tin can add together the b either after the plus sign - "r+b" - or before - "rb+")

fclose

When you're washed working with a file, yous should close information technology using the office

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 use fprintf and fscanf, both of which are like to their friends printf and scanf except that you must pass the FILE pointer every bit offset argument. For instance:

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

Information technology is also possible to read (or write) a unmarried character at a time--this can be useful if you wish to perform character-by-character input (for case, if you need to go along track of every piece of punctuation in a file information technology would brand more sense to read in a single character than to read in a string at a time.) The fgetc part, which takes a file arrow, and returns an int, volition allow you lot read a unmarried character from a file:

int fgetc (FILE *fp);        

Notice that fgetc returns an int. What this actually means is that when it reads a normal graphic symbol in the file, information technology will return a value suitable for storing in an unsigned char (basically, a number in the range 0 to 255). On the other paw, when yous're at the very cease of the file, you tin can't become a character value--in this case, fgetc will return "EOF", which is a constant that indicates that you lot've reached the end of the file. To run into a total example using fgetc in practice, take a await at the example here.

The fputc function allows you lot to write a character at a time--yous might detect this useful if you wanted to copy a file character by grapheme. It looks like this:

int fputc( int c, FILE *fp );        

Annotation that the offset argument should exist in the range of an unsigned char so that information technology is a valid grapheme. The second statement is the file to write to. On success, fputc will return the value c, and on failure, it will return EOF.

Binary file I/O - fread and fwrite

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

The declarations for each are similar:

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. Considering they accept pointers, you can also utilize these functions with other data structures; you can fifty-fifty write structs to a file or a read struct into retentiveness.

Let'south expect at i function to see how the notation works.

fread takes four arguments. Don't exist confused by the declaration of a void *ptr; void ways that information technology is a pointer that tin can be used for any type variable. The start statement is the name of the assortment or the address of the structure y'all want to write to the file. The second argument is the size of each element of the array; it is in bytes. For example, if you have an array of characters, y'all would desire to read information technology in one byte chunks, so size_of_elements is 1. Y'all tin use the sizeof operator to get the size of the diverse datatypes; for instance, if you have a variable int x; you can get the size of x with sizeof(ten);. This usage works fifty-fifty for structs or arrays. E.g., if you lot have a variable of a struct blazon with the name a_struct, y'all can employ sizeof(a_struct) to find out how much memory it is taking up.

e.m.,

sizeof(int);

The 3rd argument is but how many elements you want to read or write; for case, if you pass a 100 element array, yous desire to read no more than than 100 elements, then you pass in 100.

The final statement is simply the file pointer we've been using. When fread is used, after beingness passed an array, fread will read from the file until it has filled the array, and it will render the number of elements actually read. If the file, for example, is only 30 bytes, merely you try to read 100 bytes, it volition return that it read thirty bytes. To check to ensure the stop of file was reached, utilize the feof function, which accepts a FILE arrow and returns true if the end of the file has been reached.

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

For example,

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

Quiz yourself
Previous: Strings
Adjacent: Typecasting
Back to C Tutorial Index

Related articles

More on working with files in C

C++ file IO

Read Double Word From Binary File C++

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

0 Response to "Read Double Word From Binary File C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel