Binaries c. How to open a binary file

Description and internal representation of files

The files are different. All files stored on a computer have special attributes, i.e. special description methods that allow you to distinguish one file from another: 1) name; size 2; 3) date and time; 4)icon.

Each file has a name - the name of the file. The filename describes its contents or suggests what it can be used for. The name is assigned to the file when it is created. This applies to all files.

Each file has physical size. The file takes up some computer memory and some disk space.

When a file is created, the operating system stamps it with the date and time of creation. This allows you to sort files by date and time and thus clean up your computer. The date and time the file was updated or modified is also noted.

Each file is of a specific type, closely related to the file icon we see. The file type depends on its content. Each program assigns to the created document certain type and the corresponding icon.

The file size is measured in bytes, just like the amount of memory.

The file size can be 0 bytes, which means that the file exists, but does not contain anything in itself. S The maximum file size is 4 GB. But such huge files are very rare.

The computer's built-in clock is needed, in particular, to assign the time and date of creation to files. This explains how important it is to set this clock correctly. There are also additional attributes for describing files, such as system files, hidden files, read-only files, archive files etc. The operating system will deal with this itself.

Each file has a unique index. The index contains the information that any process needs to access the file. Processes access files using a well-defined set of system calls and identify the file with a character string that acts as the pathname of the file. Each compound name uniquely identifies a file, so the kernel translates the name into a file index. The index includes a table of addresses of the location of the file information on the disk. Since each block on the disk is addressed by its number, this table stores a collection of disk block numbers. For greater flexibility, the kernel appends one block at a time to a file, allowing the file's information to be scattered throughout. file system. But such a layout complicates the task of finding data. The address table contains a list of block numbers containing belonging to the file information, but simple calculations show that the linear list of file blocks in the index is difficult to manage. In order for a small index structure to work with big files, the disk block address table is brought into line with the structure.

Text and binary files

Files allow the user to read large amounts of data directly from the disk without typing it in from the keyboard. There are two main types of files: text and binary.

Text are called files consisting of any characters. They are organized into lines, each of which ends with the character " end of line". The end of the file itself is indicated by the symbol " end of file". When writing information to a text file, which can be viewed using any text editor, all data is converted to a character type and stored in character form.

in binary X files information is read and written in the form of blocks of a certain size, which can store data of any kind and structure.

To work with files, special data types are used, called streams. The ifstream stream is used to work with files in read mode, and ifstream in write mode. To work with files in both write and read modes, the ifstream stream is used.

In C++ programs, when working with text files, it is necessary to include the ifstream and iostream libraries.

In order to write data to a text file, you must: 1) describe type variable outstream open; 3) output information to a file; 4) be sure to close the file.

To read data from a text file, you must:

1) describe a type variable ifstream; 2) open the file using the function open; 3) read information from the file, when reading each portion of data, it is necessary to check whether the end of the file has been reached; 4) close the file.

It should be noted that in all the examples discussed above, the fopen() function in the “r” and “w” modes opens a text file for reading and writing, respectively. This means that some text formatting characters, such as the carriage return '\r', cannot be read as separate characters, no matter how they exist in the file, but they are there. This is a feature of the text file mode. For more "fine" work with the contents of files, there is a binary mode, which represents the contents of a file as a sequence of bytes, where all possible control codes are just numbers. It is in this mode that it is possible to remove or add control characters that are not available in text mode. In order to open a file in binary mode, the fopen() function is also used with the last parameter equal to “rb” and “wb”, respectively, for reading and writing.

Files. However, from the point of view technical implementation at the hardware level text files are a special case of binary files, and thus, in the broad sense of the word, any file is suitable for the definition of "binary file".

Generally this term is a measure of the relationship between the consumer of a binary file and the file itself. If the consumer knows the structure and rules by which he is able to convert a given file to a higher level one, then it is not binary for him. For example, executable files are binary for the computer user, but are not binary for the operating system. [ ]

Visualization

For a visual representation of a binary file, it is divided into pieces of equal size, represented as numbers, usually written in hexadecimal, sometimes in octal, binary, or decimal. The indicated size of a piece can be equal to one octet, as well as two or four (in the case of splitting into pieces of several octets, the byte order adopted on the platform used is applied). The dependence of the range of represented numbers on the size of the piece is shown in the table:

octets number of bits hexadecimal octal decimal
unsigned
decimal
iconic
1 8 00

FF
000

377
0

255
-128

127
2 16 0000

FFFF
000000

177777
0

65535
-32768

32767
4 32 00000000

FFFFFFFF
00000000000

37777777777
0

4294967295
-2147483648

2147483647

Often, in addition to the numeric values ​​of the bytes, code page characters, such as ASCII, are also output. The following example shows the so-called. classic dump(octet hexadecimal representation of 16 bytes per line, with printable ASCII characters on the right) of the beginning of the Wikipedia logo PNG file:

00000000 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 |.PNG........IHDR| 00000010 00 00 00 87 00 00 00 a0 08 03 00 00 00 11 90 8f |................| 00000020 b6 00 00 00 04 67 41 4d 41 00 00 d6 d8 d4 4f 58 |.....gAMA.....OX| 00000030 32 00 00 00 19 74 45 58 74 53 6f 66 74 77 61 72 |2....tEXtSoftwar| 00000040 65 00 41 64 6f 62 65 20 49 6d 61 67 65 52 65 61 |e.Adobe ImageRea| 00000050 64 79 71 c9 65 3c 00 00 03 00 50 4c 54 45 22 22 |dyq.e<....PLTE""| 00000060 22 56 56 56 47 47 47 33 33 33 30 30 30 42 42 42 |"VVVGGG333000BBB| 00000070 4b 4b 4b 40 40 40 15 15 15 4f 4f 4f 2c 2c 2c 3c |[email protected]@@...ooo,<| 00000080 3c 3c 3e 3e 3e 3a 39 39 04 04 04 1d 1d 1d 35 35 |<<>>>:99......55| 00000090 35 51 50 50 37 37 37 11 11 11 25 25 25 0d 0d 0d |5QPP777...%%%...| 000000a0 27 27 27 1a 1a 1a 38 38 38 2a 2a 2a 08 08 08 20 |"""...888**... | .............|

Instruments

For visualization

  • debug (on Microsoft Windows, partially)
  • hexdump (in FreeBSD , GNU/Linux etc.)

For editing

  • HEX editor
    • beye (for all operating systems, free software)
    • hiew (for DOS, Microsoft Windows, Windows NT)
    • WinHex (for Windows)

Tags: Binaries, fseek, ftell, fpos, fread, fwrite

Binaries

Text files store data as text (sic!). This means that if, for example, we write the integer 12345678 to a file, then 8 characters are written, which is 8 bytes of data, despite the fact that the number is placed in the integer type. In addition, the output and input of data is formatted, that is, every time we read a number from a file or write to a file, the number is transformed into a string or vice versa. These are costly operations that can be avoided.

Text files allow you to store information in a human-readable form. It is possible, however, to store data directly in binary form. For these purposes, binary files are used.

#include #include #include #define ERROR_FILE_OPEN -3 void main() ( FILE *output = NULL; int number; output = fopen("D:/c/output.bin", "wb"); if (output == NULL) ( printf(" Error opening file"); getch(); exit(ERROR_FILE_OPEN); ) scanf("%d", &number); fwrite(&number, sizeof(int), 1, output); fclose(output); _getch(); )

Run the program and look at the contents of the output.bin file. The number entered by the user is written to the file directly in binary form. You can open the file in any editor that supports hexadecimal representation (Total Commander, Far) and see for yourself.

Writing to a file is done using the function

Size_t fwrite(const void * ptr, size_t size, size_t count, FILE * stream);

The function returns the number of successfully written elements. It takes as arguments a pointer to an array, the size of one element, the number of elements, and a pointer to the file stream. Instead of an array, of course, any object can be passed.

Recording in binary file object is similar to its display: data is taken from RAM and written as is. The fread function is used to read

Size_t fread(void * ptr, size_t size, size_t count, FILE * stream);

The function returns the number of successfully read elements that are placed at ptr. In total, count elements are read by size bytes. Let's now read our number back into a variable.

#include #include #include #define ERROR_FILE_OPEN -3 void main() ( FILE *input = NULL; int number; input = fopen("D:/c/output.bin", "rb"); if (input == NULL) ( printf(" Error opening file"); getch(); exit(ERROR_FILE_OPEN); ) fread(&number, sizeof(int), 1, input); printf("%d", number); fclose(input); _getch(); )

fseek

One of the important functions for working with binary files is the fseek function.

int fseek(FILE *stream, long int offset, int origin);

This function sets the position pointer associated with the stream to a new position. The position indicator indicates where we left off in the file. When we open a file, the position is 0. Each time we write a byte of data, the position pointer moves forward by one.
fseek takes as arguments a pointer to a stream and an offset of offset bytes from origin. origin can take three values

  • SEEK_SET- the beginning of the file
  • SEEK_CUR- current file position
  • SEEK_END- end of file. Unfortunately, the standard doesn't define what end-of-file means, so you can't rely on this feature.

On success, the function returns 0.

Let's add to our old example: write a number, then move the pointer to the beginning of the file and read it.

#include #include #include #define ERROR_FILE_OPEN -3 void main() ( FILE *iofile = NULL; int number; iofile = fopen("D:/c/output.bin", "w+b"); if (iofile == NULL) ( printf ("Error opening file"); getch(); exit(ERROR_FILE_OPEN); ) scanf("%d", &number); fwrite(&number, sizeof(int), 1, iofile); fseek(iofile, 0, SEEK_SET) ; number = 0; fread(&number, sizeof(int), 1, iofile); printf("%d", number); fclose(iofile); _getch(); )

Instead, you can also use the rewind function, which moves the position indicator to the beginning.

C defines a special type, fpos_t, which is used to store the position of the position indicator in a file.
Function

int fgetpos(FILE*stream, fpos_t*pos);

is used to assign the current position to the pos variable. Function

int fsetpos(FILE * stream, const fpos_t * pos);

is used to move the pointer to the position stored in the pos variable. Both functions return zero on success.

Long int ftell(FILE*stream);

returns the current position of the indicator relative to the beginning of the file. For binary files, this is the number of bytes, for text files it is not defined (if the text file consists of single-byte characters, then also the number of bytes).

Let's consider an example: the user enters numbers. First 4 bytes of the file: an integer that indicates how many numbers were entered. After the user stops entering numbers, we move to the beginning of the file and write the number of elements entered there.

#include #include #include #define ERROR_OPEN_FILE -3 void main() ( FILE *iofile = NULL; unsigned counter = 0; int num; int yn; iofile = fopen("D:/c/numbers.bin", "w+b"); if (iofile == NULL) ( printf("Error opening file"); getch(); exit(ERROR_OPEN_FILE); ) fwrite(&counter, sizeof(int), 1, iofile); do ( printf("enter new number? " ); scanf("%d", &yn); if (yn == 1) ( scanf("%d", &num); fwrite(&num, sizeof(int), 1, iofile); counter++; ) else ( rewind (iofile); fwrite(&counter, sizeof(int), 1, iofile); break; ) ) while(1); fclose(iofile); getch(); )

The second program first reads the number of written numbers, and then reads and outputs the numbers in order.

#include #include #include #define ERROR_OPEN_FILE -3 void main() ( FILE *iofile = NULL; unsigned counter; int i, num; iofile = fopen("D:/c/numbers.bin", "rb"); if (iofile == NULL ) ( printf("Error opening file"); getch(); exit(ERROR_OPEN_FILE); ) fread(&counter, sizeof(int), 1, iofile); for (i = 0; i< counter; i++) { fread(&num, sizeof(int), 1, iofile); printf("%d\n", num); } fclose(iofile); getch(); }

Examples

1. There is a binary file of 10*sizeof(int) bytes. The user enters a cell number, and then writes a number into it. After each operation, all numbers are displayed. First, we try to open the file in read-write mode. If this fails, then we try to create a file, if it is possible to create a file, then we try again to open the file for reading and writing.

#include #include #include #define SIZE 10 void main() ( const char filename = "D:/c/state"; FILE *bfile = NULL; int pos; int value = 0; int i; char wasCreated; do ( wasCreated = 0; bfile = fopen(filename, "r+b"); if (NULL == bfile) ( printf("Try to create file...\n"); getch(); bfile = fopen(filename, "wb"); if (bfile == NULL) ( printf("Error when create file"); getch(); exit(1); ) for (i = 0; i< SIZE; i++) { fwrite(&value, sizeof(int), 1, bfile); } printf("File created successfully...\n"); fclose(bfile); wasCreated = 1; } } while(wasCreated); do { printf("Enter position "); scanf("%d", &pos); if (pos < 0 || pos >= SIZE) ( break; ) printf("Enter value "(!LANG:); scanf("%d", &value); fseek(bfile, pos*sizeof(int), SEEK_SET); fwrite(&value, sizeof(int), 1, bfile); rewind(bfile); for (i = 0; i !}< SIZE; i++) { fread(&value, sizeof(int), 1, bfile); printf("%d ", value); } printf("\n"); } while(1); fclose(bfile); }

2. We write words to a binary file. The format is as follows - first the number of letters, then the word itself without the null character. If the word length is zero, then more words no. First, we ask the user for words, then we read them back.

#include #include #include #include #define ERROR_FILE_OPEN -3 void main() ( const char filename = "C:/c/words.bin"; const char termWord = "exit"; char buffer; unsigned int len; FILE *wordsFile = NULL; printf("Opening file...\n"); wordsFile = fopen(filename, "w+b"); if (wordsFile == NULL) ( printf("Error opening file"); getch(); exit(ERROR_FILE_OPEN); ) printf ("Enter words\n"); do ( scanf("%127s", buffer); if (strcmp(buffer, termWord) == 0) ( len = 0; fwrite(&len, sizeof(unsigned), 1, wordsFile ); break; ) len = strlen(buffer); fwrite(&len, sizeof(unsigned), 1, wordsFile); fwrite(buffer, 1, len, wordsFile); ) while(1); printf("rewind and read words \n"); rewind(wordsFile); getch(); do ( fread(&len, sizeof(int), 1, wordsFile); if (len == 0) ( break; ) fread(buffer, 1, len, wordsFile ); buffer = "\0"; printf("%s\n", buffer); ) while(1); fclose(wordsFile); getch(); )

3. The task is to read data from a text file and write it to a binary file. To solve the problem, let's create a wrapper function. It will accept a file name, an access mode, a function to execute if the file was successfully opened, and arguments to that function. Since there can be many arguments and they can be of different types, they can be passed as a pointer to a structure. After the function is executed, the file is closed. Thus, there is no need to think about releasing resources.

#include #include #include #define DEBUG #ifdef DEBUG #define debug(data) printf("%s", data); #else #define debug(data) #endif const char inputFile = "D:/c/xinput.txt"; const char outputFile = "D:/c/output.bin"; struct someArgs ( int* items; size_t number; ); int writeToFile(FILE *file, void* args) ( size_t i; struct someArgs *data = (struct someArgs*) args; debug("write to file\n") fwrite(data->items, sizeof(int), data ->number, file); debug("write finished\n") return 0; ) int readAndCallback(FILE *file, void* args) ( struct someArgs data; size_t size, i = 0; int result; debug("read from file\n") fscanf(file, "%d", &size); data.items = (int*) malloc(size*sizeof(int)); data.number = size; while (!feof(file)) ( fscanf(file, "%d", &data.items[i]); i++; ) debug("call withOpenFile\n") result = withOpenFile(outputFile, "w", writeToFile, &data); debug("read finish \n") free(data.items); return result; ) int doStuff() ( return withOpenFile(inputFile, "r", readAndCallback, NULL); ) //Wrapper - the function opens a file. If the file was successfully opened, //the fun function is called. Since the arguments can be very different, //they are passed through the void* pointer. As an argument type // it is reasonable to use the structure int withOpenFile(const char *filename, const char *mode, int (*fun)(FILE* source, void* args), void* args) ( FILE *file = fopen(filename, mode); int err; debug("try to open file ") debug(filename) debug("\n") if (file != NULL) ( err = fun(file, args); ) else ( return 1; ) debug("close file ") debug(filename) debug("\n") fclose(file); return err; ) void main() ( printf("result = %d", doStuff()); getch(); )

4. The saveInt32Array function allows you to save an array of type int32_t to a file. The inverse of loadInt32Array reads the array back. The loadInt32Array function first initializes the array passed to it, so we must pass a pointer to a pointer; in addition, it writes the read size of the array to the passed size parameter, which is why it is passed as a pointer.

#include #include #include #include #define SIZE 100 int saveInt32Array(const char *filename, const int32_t *a, size_t size) ( FILE *out = fopen(filename, "wb"); if (!out) ( return 0; ) //Write array length fwrite (&size, sizeof(size_t), 1, out); //Write the entire array fwrite(a, sizeof(int32_t), size, out); fclose(out); return 1; ) int loadInt32Array(const char *filename, int32_t **a, size_t *size) ( FILE *in = fopen(filename, "rb"); if (!in) ( return 0; ) //Read the length of the array fread(size, sizeof(size_t), 1, in) ; //Initialize the array (*a) = (int32_t*) malloc(sizeof(int32_t) * (*size)); if (!(*a)) ( return 0; ) //Read the entire array fread((*a ), sizeof(int32_t), *size, in); fclose(in); return 1; ) void main() ( const char *tmpFilename = "tmp.bin"; int32_t exOut; int32_t *exIn = NULL; size_t realSize; int i; for (i = 0; i< SIZE; i++) { exOut[i] = i*i; } saveInt32Array(tmpFilename, exOut, SIZE); loadInt32Array(tmpFilename, &exIn, &realSize); for (i = 0; i < realSize; i++) { printf("%d ", exIn[i]); } _getch(); }

5. Create a lookup table. To speed up the program, instead of calculating a function, you can first calculate the values ​​of the function on an interval with a certain accuracy, and then take the values ​​already from the table. The program first tabulates the function with given parameters and saves it to a file, then loads the precomputed array that is already used to determine the values. In this program, all functions return a variable of type Result, which stores the error number. If the function worked without problems, then it returns Ok (0).

#define _CRT_SECURE_NO_WARNINGS //Yes, this is now mandatory to add, otherwise it won't work #include #include #include #include #include //Each function returns a result. If it is equal to Ok, then the function //worked without problems typedef int Result; //Possible results of work #define Ok 0 #define ERROR_OPENING_FILE 1 #define ERROR_OUT_OF_MEMORY 2 //The function that we will tabulate double mySinus(double x) ( return sin(x); ) Result tabFunction(const char *filename, double from, double to, double step, double (*f)(double)) ( Result r; FILE *out = fopen(filename, "wb"); double value; if (!out) ( r = ERROR_OPENING_FILE; goto EXIT; ) fwrite (&from, sizeof(from), 1, out); fwrite(&to, sizeof(to), 1, out); fwrite(&step, sizeof(step), 1, out); for (from; from< to; from += step) { value = f(from); fwrite(&value, sizeof(double), 1, out); } r = Ok; EXIT: fclose(out); return r; } Result loadFunction(const char *filename, double **a, double *from, double *to, double *step) { Result r; uintptr_t size; FILE *in = fopen(filename, "rb"); if (!in) { r = ERROR_OPENING_FILE; goto EXIT; } //Считываем вспомогательную информацию fread(from, sizeof(*from), 1, in); fread(to, sizeof(*to), 1, in); fread(step, sizeof(*step), 1, in); //Инициализируем массив size = (uintptr_t) ((*to - *from) / *step); (*a) = (double*) malloc(sizeof(double)* size); if (!(*a)) { r = ERROR_OUT_OF_MEMORY; goto EXIT; } //Считываем весь массив fread((*a), sizeof(double), size, in); r = Ok; EXIT: fclose(in); return r; } void main() { const char *tmpFilename = "tmp.bin"; Result r; double *exIn = NULL; int accuracy, option; double from, to, step, arg; uintptr_t index; //Запрашиваем параметры для создания таблицы поиска printf("Enter parameters\nfrom = "); scanf("%lf", &from); printf("to = "); scanf("%lf", &to); printf("step = "); scanf("%lf", &step); r = tabFunction(tmpFilename, from, to, step, mySinus); if (r != Ok) { goto CATCH_SAVE_FUNCTION; } //Обратите внимание на формат вывода. Точность определяется //во время работы программы. Формат * подставит значение точности, //взяв его из списка аргументов accuracy = (int) (-log10(step)); printf("function tabulated from %.*lf to %.*lf with accuracy %.*lf\n", accuracy, from, accuracy, to, accuracy, step); r = loadFunction(tmpFilename, &exIn, &from, &to, &step); if (r != Ok) { goto CATCH_LOAD_FUNCTION; } accuracy = (int)(-log10(step)); do { printf("1 to enter values, 0 to exit: "); scanf("%d", &option); if (option == 0) { break; } else if (option != 1) { continue; } printf("Enter value from %.*lf to %.*lf: ", accuracy, from, accuracy, to); scanf("%lf", &arg); if (arg < from || arg >to) ( printf("bad value\n"); continue; ) index = (uintptr_t) ((arg - from) / step); printf("saved %.*lf\ncomputed %.*lf\n", accuracy, exIn, accuracy, mySinus(arg)); ) while(1); r = Ok; goto EXIT; CATCH_SAVE_FUNCTION: ( printf("Error while saving values"); goto EXIT; ) CATCH_LOAD_FUNCTION: ( printf("Error while loading values"); goto EXIT; ) EXIT: free(exIn); _getch(); exit(r); )

6. We have two structures. The first PersonKey stores the username, password, user id, and the offset field. The second PersonInfo structure stores the user's first and last name and their age. The first structures are written to the binary file keys.bin, the second structures to the binary file values.bin. The offset field specifies the position of the corresponding user information in the second file. Thus, having received the PersonKey from the first file, the offset field can be used to extract the information related to this key from the second file.

Why do this? This is beneficial if the PersonInfo structure is large. Extracting an array of small structures from a file is not expensive, and when we need a large structure, we can extract it at an already known address in the file.

#define _CRT_SECURE_NO_WARNINGS #include #include #include #include typedef struct PersonKey ( long long id; char login; char password; long offset;//Position of corresponding PersonInfo values) PersonKey; typedef struct PersonInfo ( unsigned age; char firstName; char lastName; ) PersonInfo; /* The function asks the user for data and writes them to two files in a row */ void createOnePerson(FILE *keys, FILE *values) ( static long long id = 0; PersonKey pkey; PersonInfo pinfo; pkey.id = id++; //So as all values ​​are written one after another, then the current position // of the pointer in the second file will be the position for new entry pkey.offset = ftell(values); printf("login: "); scanf("%63s", pkey.login); printf("Password: "); scanf("%63s", pkey.password); printf("age: "); scanf("%d", &(pinfo.age)); printf("First Name: "); scanf("%63s", pinfo.firstName); printf("Last Name: "); scanf("%127s", pininfo.lastName); fwrite(&pkey, sizeof(pkey), 1, keys); fwrite(&pinfo, sizeof(pinfo), 1, values); ) void createPersons(FILE *keys, FILE *values) ( char buffer; int repeat = 1; int counter = 0;//Number of elements in the file //Reserve space for recording the number of elements fwrite(&counter, sizeof(counter), 1 , keys); printf("CREATE PERSONS\n"); do ( createOnePerson(keys, values); printf("\nYet another one? "); scanf("%1s", buffer); counter++; if (buffer ! = "y" && buffer != "Y") ( repeat = 0; ) ) while(repeat); //Go back and write the number of elements created rewind(keys); fwrite(&counter, sizeof(counter), 1, keys); ) /* Create an array of keys */ PersonKey* readKeys(FILE *keys, int *size) ( int i; PersonKey *out = NULL; rewind(keys); fread(size, sizeof(*size), 1, keys); out = (PersonKey*) malloc(*size * sizeof(PersonKey)); fread(out, sizeof(PersonKey), *size, keys); return out; ) /* The function opens two files at once. To simplify the task, we return an array of files. */ FILE** openFiles(const char *keysFilename, const char *valuesFilename) ( FILE **files = (FILE**)malloc(sizeof(FILE*)*2); files = fopen(keysFilename, "w+b" ); if (!files) ( return NULL; ) files = fopen(valuesFilename, "w+b"); if (!files) ( fclose(files); return NULL; ) return files; ) /* Two secondary functions to print key and info */ void printKey(PersonKey pk) ( printf("%d. %s [%s]\n", (int)pk.id, pk.login, pk.password); ) void printInfo( PersonInfo info) ( printf("%d %s %s\n", info.age, info.firstName, info.lastName); ) /* The function by key (or rather, by its offset field) gets the desired value from the second file */ PersonInfo readInfoByPersonKey(PersonKey pk, FILE *values) ( PersonInfo out; rewind(values); fseek(values, pk.offset, SEEK_SET); fread(&out, sizeof(PersonInfo), 1, values); return out; ) void getPersonsInfo(PersonKey *keys, FILE *values, int size) ( int index; PersonInfo p; do ( printf("Enter position of element. To exit print bad index: "); scanf("%d", &index); if (index< 0 || index >= size) ( printf("Bad index"); return; ) p = readInfoByPersonKey(keys, values); printInfo(p); ) while(1); ) void main() ( int size; int i; PersonKey *keys = NULL; FILE **files = openFiles("C:/c/keys.bin", "C:/c/values.bin"); if ( files == 0) ( printf("Error opening files"); goto FREE; ) createPersons(files, files); keys = readKeys(files, &size); for (i = 0; i< size; i++) { printKey(keys[i]); } getPersonsInfo(keys, files, size); fclose(files); fclose(files); FREE: free(files); free(keys); _getch(); }

Many people often have a question about how to open a binary file. This document is any file that is on a personal computer. All data that is on computers and media associated with it is usually recorded in bits. It is from this word that the name originated. If a simple text file is given as a comparison, then there will be no problems with reading it. To do this, it is enough to have a regular editor on your computer, even a notepad will do. To open a binary file, simple notepad can't get by. And if we talk about the fact that the information of text files is encrypted with the same bits, then usually, when they talk about reading binary files, they mean executable documents.

Instructions for action

First, on HDD personal computer you need to install software tool called HexEditor, which is a simple editor for binary files. After installation, the program should be opened by double-clicking on the icon. This tool will allow you to read a binary file in real mode. In this case, you can change the data in the file, add your own information, etc. In order to work in this editor and modify a binary file, you must have at least some knowledge in this area of ​​\u200b\u200bactivity.

Secondly, you need to familiarize yourself with its main window, which does not differ much from the window of a conventional editor. Same buttons, same menu, document body, bookmarks and status bars. You can open the file of interest through the File tab or through special button, which is located on in the program. After that, you will be able to see the executable file, which will appear in the form of numbers and letters. Do not confuse the characters with which a binary file is presented, and those that a regular editor has. In the event that a decision is made to delete or change any part of the document, it should be understood that any part of it will disappear or change.

Thirdly, with the help of the program, you can try to change any part of the document. As mentioned earlier, the tool displays the file in a way that improves the way you can find the desired part of the document. In addition, the program has enough flexible setting. With it, you can change the graphical display of the binary code that a binary file has. In the event that incorrect data is entered into some section of the file, then it may subsequently either completely stop working, or it will start to work not quite correctly. In any case, entering such data will cause changes both in the operating system and directly in the personal computer itself.

Fourthly, after changing, deleting or adding certain data in the file, you should save the result of your work. In the event that you do not have sufficient experience in editing files, then you should be prepared for not very pleasant consequences. For example, a document may stop working after data has been changed. Until you start to understand this issue well, a lot of copies of files will be corrupted. If you are not confident in your abilities, then you should not change the data yourself, especially in situations where you need to fix the su binary file.

Files. At the same time, from the point of view of technical implementation at the hardware level, text files are a special case of binary files, and, thus, in the broad sense of the word, any file is suitable for the definition of "binary file".

Binary files are often referred to as executable files and compressed data, but it is incorrect to limit this concept in this way.

Visualization

For a visual representation of a binary file, it is divided into pieces of equal size, represented as numbers, usually written in hexadecimal, sometimes in octal, binary, or decimal. The indicated size of a piece can be equal to one octet, as well as two or four (in the case of splitting into pieces of several octets, the byte order adopted on the platform used is applied). The dependence of the range of represented numbers on the size of the piece is shown in the table:

octets number of bits hexadecimal octal decimal
unsigned
decimal
iconic
1 8 00

FF
000

377
0

255
-128

127
2 16 0000

FFFF
000000

177777
0

65535
-32768

32767
4 32 00000000

FFFFFFFF
00000000000

37777777777
0

4294967295
-2147483648

2147483647

Often, in addition to the numerical values ​​of the bytes, code page characters are also displayed, for example, printed ASCII characters on the right) of the beginning of the PNG file of the Wikipedia logo:

00000000 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 |.PNG........IHDR| 00000010 00 00 00 87 00 00 00 a0 08 03 00 00 00 11 90 8f |................| 00000020 b6 00 00 00 04 67 41 4d 41 00 00 d6 d8 d4 4f 58 |.....gAMA.....OX| 00000030 32 00 00 00 19 74 45 58 74 53 6f 66 74 77 61 72 |2....tEXtSoftwar| 00000040 65 00 41 64 6f 62 65 20 49 6d 61 67 65 52 65 61 |e.Adobe ImageRea| 00000050 64 79 71 c9 65 3c 00 00 03 00 50 4c 54 45 22 22 |dyq.e<....PLTE""| 00000060 22 56 56 56 47 47 47 33 33 33 30 30 30 42 42 42 |"VVVGGG333000BBB| 00000070 4b 4b 4b 40 40 40 15 15 15 4f 4f 4f 2c 2c 2c 3c |[email protected]@@...ooo,<| 00000080 3c 3c 3e 3e 3e 3a 39 39 04 04 04 1d 1d 1d 35 35 |<<>>>:99......55| 00000090 35 51 50 50 37 37 37 11 11 11 25 25 25 0d 0d 0d |5QPP777...%%%...| 000000a0 27 27 27 1a 1a 1a 38 38 38 2a 2a 2a 08 08 08 20 |"""...888***... | ..............|

Instruments

For visualization

  • debug (on Microsoft Windows, partially)
  • hexdump (on GNU/Linux etc.)

For editing

Literature

  • Webster's New World Dictionary of Computer Terms, 4th. Ed, Prentice Hall, NY, 1992. ISBN 0-671-84651-5
  • Leontiev B.K. Microsoft Windows XP File Formats: A Handbook, M.: ZAO "New Publishing House", 2005. ISBN 5-9643-0059-6

Wikimedia Foundation. 2010 .

See what "Binary file" is in other dictionaries:

    Exist., m., use. comp. often Morphology: (no) what? file, no? file, (see) what? file what? file about what? about the file pl. what? files, (no) what? files than? files, (see) what? files than? files about what? about files 1. An array is called a file ... ... Dictionary of Dmitriev

    Binary (binary) file in the broad sense: a sequence of arbitrary bytes. The name is due to the fact that bytes consist of bits, that is, binary (English binary) digits. In the narrow sense of the word, binary files are opposed to text files. ... ... Wikipedia

    Binary (binary) file in the broad sense: a sequence of arbitrary bytes. The name is due to the fact that bytes consist of bits, that is, binary (English binary) digits. In the narrow sense of the word, binary files are opposed to ... ... Wikipedia

    configuration file- A binary or text file containing information that defines the behavior of an application, computer, or network device. Network topics computing EN configuration file … Technical Translator's Handbook

    This term has other meanings, see IPA (meanings). .IPA is an application archive file format from Apple for the iPhone, iPod Touch, and iPad. Files with this extension are stored in the App Store and downloaded using iTunes for ... ... Wikipedia

    This article or section needs revision. There are no modules, OOP and other newfangled trends in Pascal. Description of extensions should be present only in articles about corresponding ... Wikipedia

    Pascal Semantics: procedural Execution type: compiler Introduced in: 1970 Author(s): Niklaus Wirth Pascal is a general-purpose high-level programming language. One of the most famous programming languages, widely ... ... Wikipedia

    Gopher Name: Gopher Port/ID: 70/TCP Specification: RFC 1436 Main implementations (clients): Mozilla Firefox, Microsoft Windows: IE 5.x, IE 6 (limited to MS) ... Wikipedia

    Name: Gopher Port / ID: 70 / TCP Specification: RFC 1436 Main implementations (clients): Mozilla Firefox, Microsoft Windows: Internet Explorer 5.x, Internet Explorer 6 (limited to MS) Gopher distributed search and transmission network protocol ... ... Wikipedia

    - /* A B C D E F G H I J K L M N O P Q R S T U V W X Y Z