How to set up smartphones and PCs. Informational portal

Language cc. Basics C

BASES C

Introduction

Chapter 1. Basics of the C language

1.1. Alphabet

1.2. Basic C constructs

1.3. Input Output.

1.3.1. Conclusion

1.4. Basic data types of the C language

1.4.1. Identifiers.

1.4.2. Typed constants

1.4.3. Variables

1.4.3.1. Integer types

1.4.3.2. Real types

1.4.3.3. Character types

1.4.4. Data type string

1.4.5. Structures

1.4.5.1. Arrays

1.4.5.2. Recordings

1.4.6 Scope and lifetime of variables

1.5. Basic Operators

1.6. Preprocessor

1.7. Programs. Functions

1.8. Pointers

1.9. Pointers and Functions

1.10. Files

1.11. Additional C functions

1.11.1. Conversion functions

Functions for converting character strings: atoi (), atof (). 37s.

1.11.3. Functions that work with strings

1.12. Features of C programming

1.12.1. Modules. Multimodal programming

1.12.2. Memory models

1.12.3. DOS and Windows Programming

1.12.4. Using assembly language in C programs

Chapter 2. Examples of using the C language

2.1. Sorting

2.2. Recursive algorithms

2.3. The challenge "Towers of Hanoi"

Chapter 3. C ++ Basics

3.1. Differences between C ++ and C

3.2. Object Oriented Programming in C ++

3.2.1. Classes

3.2.2. Overloading functions

3.2.3. Constructors

3.2.4. Destructors

3.2.5. Parameterized constructors

3.2.6. Introduction to inheritance

3.2.7. Virtual functions

3.2.8. Object pointers

Chapter 4. Fundamentals of C ++ Builder Programming

4.1. Characteristic of C ++ Builder

4.2. VCL components. Properties. Events. Methods

4.2.1. Component types

4.2.2. VCL class hierarchy

4.3. File structure in C ++ Builder

4.4. Visual Components (VCL)

4.5. Programs, event management, exceptions

4.6. Debugging strategy for Windows programs

4.7. Using VCL Components in Program Development

4.8. Graphics components.

4.9. Multimedia

4.10. Sprite graphics

4.11. OLE2 Object Technology

4.12. DLLs.

4.13. Development of visual components

4.14. Introduction to CGI Programming

3.15. Database programming.

3.16. Packages

Conclusion

Literature

Appendix N1

Introduction

In 1804, the French inventor Joseph Marie Jacquard created a "software-controlled" loom. To control the machine, punch cards were used, connected to each other in the form of a tape. The wooden pins of the "reading device" of the machine, by the location of the holes in the punched card, determined which threads should be raised and which ones should be lowered to obtain the desired pattern.

In 1890, in the United States, inventor Herman Hollerith developed an electromechanical calculating machine - a tabulator controlled by punched cards, was used to compile tables with the results of the US census. The Hollerith-founded tabulator firm later became International Business Machines Corporation (IBM).

In 1936, Alan Turing, a 25-year-old student at Cambridge University, published an article "On Computable Numbers", which considered a hypothetical device ("Turing machine") suitable for solving any solvable mathematical or logical problem - the prototype of a programmable computer.

In 1941, German engineer Konrad Zuse built a working Z3 computer that used the binary number system. The programs were recorded on punched tape.

In 1945, physicist John Mauchly and engineer Prosper Eckert built an all-electronic Eniak machine at the Graduate School of Technology at the University of Pennsylvania (USA). To set the program, it was necessary to manually set thousands of switches and plug hundreds of plugs into the sockets of the contact panel.

On June 1, 1945, a report was sent out by the Hungarian-American mathematician John von Neumann, A Preliminary Report on the Edvak Machine, containing the concept of storing computer instructions in its own internal memory.

On June 21, 1948, at the University of Manchester (Great Britain), on the Mark-1 machine, the world's first program stored in the memory of the machine was executed - the search for the largest factor of a given number.

In 1949, under the leadership of Maurice Wilkes, the Edsack computer was created. Edsak's designers introduced a system of mnemonic notation, where each machine instruction was represented by one capital letter, and automated the tuning of subroutines to a specific place in memory. Maurice Wilkes called the mnemonic diagram and subroutine library the assembly system - hence the word "assembler".

In 1949, in Philadelphia (USA), under the leadership of John Mauchly, "Short Code" was created - the first primitive interpreter of the programming language.

In 1951, American programmer Grace Hopper developed the first broadcasting program at the Remington Rand firm. Hopper called it a compiler.

In 1957, FORmula TRANslation (FORmula TRANslation) was born on the 20th floor of the IBM headquarters on Madison Avenue in New York. The development team was led by 30-year-old mathematician John Backus. Fortran is the first of the "true" high-level languages.

In 1972, 31-year-old systems programmer at Bell Labs, Dennis Ritchie, developed the C programming language.

In 1984, the French mathematician and saxophonist Philippe Kahn founds Borland International.

C was originally designed as a programming language for the Unix operating system.

It soon began to spread to practicing programmers. In the late 70s, C translators for Microcomputers were developed for the CP / M operating system.

After the appearance of the IBM PC, C compilers began to appear (there are now more than 20 of them for this computer).

In 1983, the American Standards Institute (ANSI) formed the X3J11 Technical Committee to create the C language standard. Borland's C ++ language, which appeared on the market, obeys most of the requirements of the standard.

At its core, C is a function language. C programming is carried out by writing functions and calling library functions. Most functions return some value that can be used in other operators.

Among the many advantages of the C language, the main ones should be noted:


Versatility (used on almost all existing computers);

Compactness and versatility of the code;

Speed ​​of program execution;

Language flexibility;

High structuredness.


Chapter 1. Basics of the C language

1.1. Alphabet

The language alphabet consists of the following characters:

Uppercase and lowercase Latin letters A-Z, a-z and the underscore character. Digits from 0 to 9. Special characters + - * / =>< . ; , : { } () # $.

The characters space, tab, line feed, carriage return are called spaces.

A C ++ program is a sequence of ACSII characters that represent its source text.

1.2. Basic C constructs

Consider a simple program for printing the phrase "Hello from the computer" on the screen

#include

// program

printf ("Greetings from the computer \ n");

Consider the structure of the program

The #include command includes the stdio.h file in our program. The file contains information about the I / O functions.

A file named stdio.h contains I / O information.

The # symbol indicates that before translating the program, it is necessary to include functions from the stdio.h file in it - this is the so-called preprocessing processing, which performs some preprocessing of the program text before compiling.

The main () line contains the name of the function that the program always starts with. Empty brackets indicate that this is a function, but it has no parameters.

The // symbols are followed by comments (for one line), (symbols between / * and * / are also called comments).

Curly braces () mark the beginning and end of the body of a program or function. They are also used to combine multiple program statements into a block.

The line printf ("Greetings from the computer \ n") contains the standard C print function. The character string enclosed in parentheses (argument) is the information passed to printf () from our main function main (). When the function is completed, control will return back to the original program. The \ n character denotes a line feed on a new line after printing.

Consider the following example - write a program for converting meters to centimeters.

#include

#include

printf ("M? \ n");

printf ("% d M contains% d cm \ n", I, J);

This program defines two integer variables I and J.

The scanf function has been introduced ("% d", & I); which allows you to enter a decimal number from the keyboard and assign the value to the variable I, then by the command J = 100 * I; calculation in progress 4.

Next line printf ("% d M contains% d cm \ n", I, J); prints the phrase. The first% d (d is an integer variable) is replaced by the value I, the second% d is replaced by the value J.

The getch () function allows you to freeze the image on the screen and requires any character to complete the job.

Let's look at another example. Let's write a function and call it from our program.

#include

#include

printf ("Did you call me? \ n");

printf ("I am calling the supervisor function. \ n");

printf ("Yes. See which student is asleep and wake them up. \ n");

Fundamentals and subtleties of the C ++ programming language. Practical assignments and tests. Do you want to learn to program? Then you are at the right place. It doesn't matter if you have programming experience or not, these tutorials will help you get started building, compiling and debugging C ++ programs in different development environments: Visual Studio, Code :: Blocks, Xcode, Eclipse, and other IDEs. Lots of examples and detailed explanations. Perfect for both beginners (dummies) and more advanced ones. Everything is explained from scratch to the very details. These (200+) tutorials will give you a good foundation / foundation in understanding programming not only in C ++, but in other languages ​​as well. And it's completely free!

All you need is a desire, a desire to learn. Everything else you can find here.

For repost +20 karma and my thanks!

Chapter # 0. Introduction. Beginning of work

Chapter # 1. C ++ Basics

Chapter # 2. Variables and Basic Data Types in C ++

Chapter # 3. Operators in C ++

Chapter # 4. Scope and other types of variables in C ++

These tutorials are for everyone, whether you are new to programming or have extensive programming experience in other languages! This material is for those who want to learn the C / C ++ languages ​​from its very foundations to the most complex structures.

C ++ is a programming language, knowledge of this programming language will allow you to control your computer at the highest level. Ideally, you can get the computer to do whatever you want. Our site will help you in mastering the C ++ programming language.

Installation / IDE

The very first thing you should do before you start learning C ++ is to make sure you have an IDE - an integrated development environment (the program in which you will be programming). If you don't have an IDE, then this is the place for you. Once you've decided on an IDE, install it and practice creating simple projects.

Introduction to the C ++ language

C ++ is a set of commands that tell the computer what to do. This set of commands is usually called source code or just code. Commands are either "functions" or "keywords". Keywords (C / C ++ reserved words) are the basic building blocks of the language. Functions are complex building blocks because they are written in terms of simpler functions - you will see this in our very first program, which is shown below. This structure of functions resembles the content of a book. The table of contents can show the chapters of the book, each chapter in the book can have its own table of contents, consisting of paragraphs, each paragraph can have its own sub-paragraphs. Although C ++ provides many common functions and reserved words that you can use, there is still a need to write your own functions.

Where is the beginning of the program? Each program in C ++ has one function, it is called the main or main-function, the execution of the program begins with this function. From the main function, you can also call any other functions, it doesn't matter if they are written by us, or, as mentioned earlier, are provided by the compiler.

So how do you access these Standard Features? To access the standard functions that come with the compiler, you need to include the header file using the preprocessor directive - #include. Why is it effective? Let's take a look at an example of a working program:

#include << "Моя первая программа на С++\n"; cin.get(); }

Let's consider in detail the elements of the program. #include is a preprocessor directive that tells the compiler to put the code from the iostream header file into our program before creating the executable. By connecting the header file to the program, you get access to many different functions that you can use in your program. For example, the cout operator requires an iostream. The line using namespace std; tells the compiler to use a group of functions that are part of the std standard library. This line also allows the program to use statements such as cout. The semicolon is part of the C ++ syntax. It tells the compiler that this is the end of the command. You will see later that semicolons are used to complete most commands in C ++.

The next important line of the program is int main (). This line tells the compiler that there is a function named main, and that the function returns an integer of type int. The curly braces (and) signal the start (and end) of a function. Curly braces are used in other blocks of code, but they always mean the same thing - the beginning and the end of the block, respectively.

In C ++, the cout object is used to display text (pronounced C out). He uses symbols<< , известные как «оператор сдвига», чтобы указать, что отправляется к выводу на экран. Результатом вызова функции cout << является отображение текста на экране. Последовательность \n фактически рассматривается как единый символ, который обозначает новую строку (мы поговорим об этом позже более подробно). Символ \n перемещает курсор на экране на следующую строку. Опять же, обратите внимание на точку с запятой, её добавляют в конец, после каждого оператора С++.

The next command is cin.get (). This is another function call that reads data from an input data stream and waits for the ENTER key to be pressed. This command keeps the console window from closing until the ENTER key is pressed. This gives you time to see the output of the program.

Upon reaching the end of the main function (closing curly brace), our program will return 0 for the operating system. This return value is important because, by analyzing it, the OS can judge whether our program completed successfully or not. A return value of 0 means success and is returned automatically (but only for the int data type, other functions require you to manually return a value), but if we wanted to return something else, for example 1, we would have to do it manually.

#include using namespace std; int main () (cout<<"Моя первая программа на С++\n"; cin.get(); return 1; }

To consolidate the material, type the program code in your IDE and run it. After the program has started and you see the results, experiment a little with the cout statement. This will help you get used to the language.

Be sure to comment on your programs!

Add comments to the code to make it clearer not only for yourself but also for others. The compiler ignores comments when executing code, which allows any number of comments to be used to describe the actual code. To create a comment, use either //, which tells the compiler that the rest of the line is a comment, or / * and then * /. When you learn to program, it is useful to be able to comment on certain sections of the code in order to see how the result of the program's work changes. You can read about the commenting technique in detail.

What to do with all these types of variables?

It can be confusing at times to have multiple types of variables when it seems that some types of variables are redundant. It is very important to use the correct variable type, as some variables require more memory than others. In addition, because of the way they are stored in memory, floating point numbers, the float and double data types are "imprecise" and should not be used when an exact integer value must be stored.

Declaring Variables in C ++

To declare a variable, use the syntax type<имя>; ... Here are some examples of variable declarations:

Int num; char character; float num_float;

It is permissible to declare several variables of the same type on one line; for this, each of them must be separated by a comma.

Int x, y, z, d;

If you've looked closely, you may have seen that a variable declaration is always followed by a semicolon. You can learn more about the convention - "about naming variables".

Common mistakes when declaring variables in C ++

If you try to use a variable that you have not declared, your program will not compile and you will receive an error message. In C ++, all language keywords, all functions, and all variables are case sensitive.

Using Variables

So now you know how to declare a variable. Here's a sample program that demonstrates the use of a variable:

#include using namespace std; int main () (int number; cout<< "Введите число: "; cin >> number; cin.ignore (); cout<< "Вы ввели: "<< number <<"\n"; cin.get(); }

Let's walk through this program and examine its code, line by line. The int keyword says that number is an integer. The cin >> function reads a value into number, the user must press enter after the entered number. cin.ignore () is a function that reads a character and ignores it. We have organized our input into the program, after entering a number, we press the ENTER key, which is also passed to the input stream. We don't need this, so we discard it. Keep in mind that the variable was declared of an integer type, if the user tries to enter a decimal number, it will be truncated (that is, the decimal part of the number will be ignored). Try to enter a decimal number or a sequence of characters, when you run the sample program, the answer will depend on the input value.

Note that quotes are not used when printing from a variable. The absence of quotes tells the compiler that there is a variable, and therefore that the program should check the value of the variable in order to replace the name of the variable with its value at runtime. Multiple shift operators on the same line are fine and the output will be done in the same order. You must separate string literals (quoted strings) and variables, giving each a different shift operator<< . Попытка поставить две переменные вместе с одним оператором сдвига << выдаст сообщение об ошибке . Не забудьте поставить точку с запятой. Если вы забыли про точку с запятой, компилятор выдаст вам сообщение об ошибке при попытке скомпилировать программу.

Changing and comparing values

Of course, no matter what data type you are using, variables are of little interest without the ability to change their value. The following are some of the operators used in conjunction with variables:

  • * multiplication,
  • - subtraction,
  • + addition,
  • / division,
  • = assignment,
  • == equality,
  • > more,
  • < меньше.
  • ! = unequal
  • > = greater than or equal
  • <= меньше или равно

Operators that perform mathematical functions must be used to the right of the assignment sign, in order to assign the result to a variable on the left.

Here are some examples:

A = 4 * 6; // use line comment and semicolon, a equals 24 a = a + 5; // is equal to the sum of the original value and five a == 5 // five is not assigned, it is checked whether it is 5 or not

You will often use == in constructs such as conditionals and loops.

A< 5 // Проверка, a менее пяти? a >5 // Check if a is greater than five? a == 5 // Check if a is five? a! = 5 // Check, but not equal to five? a> = 5 // Check if a is greater than or equal to five? a<= 5 // Проверка, a меньше или равно пяти?

These examples are not very clear about the use of comparison signs, but when we begin to study the selection operators, you will understand why this is necessary.

Department: Automation and Information Technologies

BASES C

Introduction

Chapter 1. Basics of the C language

1.1. Alphabet

1.2. Basic C constructs

1.3. Input Output.

1.3.1. Conclusion

1.4. Basic data types of the C language

1.4.1. Identifiers.

1.4.2. Typed constants

1.4.3. Variables

1.4.3.1. Integer types

1.4.3.2. Real types

1.4.3.3. Character types

1.4.4. Data type string

1.4.5. Structures

1.4.5.1. Arrays

1.4.5.2. Recordings

1.4.6 Scope and lifetime of variables

1.5. Basic Operators

1.6. Preprocessor

1.7. Programs. Functions

1.8. Pointers

1.9. Pointers and Functions

1.10. Files

1.11. Additional C functions

1.11.1. Conversion functions

Functions for converting character strings: atoi (), atof (). 37s.

1.11.3. Functions that work with strings

1.12. Features of C programming

1.12.1. Modules. Multimodal programming

1.12.2. Memory models

1.12.3. DOS and Windows Programming

1.12.4. Using assembly language in C programs

Chapter 2. Examples of using the C language

2.1. Sorting

2.2. Recursive algorithms

2.3. The challenge "Towers of Hanoi"

Chapter 3. C ++ Basics

3.1. Differences between C ++ and C

3.2. Object Oriented Programming in C ++

3.2.1. Classes

3.2.2. Overloading functions

3.2.3. Constructors

3.2.4. Destructors

3.2.5. Parameterized constructors

3.2.6. Introduction to inheritance

3.2.7. Virtual functions

3.2.8. Object pointers

Chapter 4. Fundamentals of C ++ Builder Programming

4.1. Characteristic of C ++ Builder

4.2. VCL components. Properties. Events. Methods

4.2.1. Component types

4.2.2. VCL class hierarchy

4.3. File structure in C ++ Builder

4.4. Visual Components (VCL)

4.5. Programs, event management, exceptions

4.6. Debugging strategy for Windows programs

4.7. Using VCL Components in Program Development

4.8. Graphics components.

4.9. Multimedia

4.10. Sprite graphics

4.11. OLE2 Object Technology

4.12. DLLs.

4.13. Development of visual components

4.14. Introduction to CGI Programming

3.15. Database programming.

3.16. Packages

Conclusion

Literature

Appendix N1


Introduction

In 1804, the French inventor Joseph Marie Jacquard created a "software-controlled" loom. To control the machine, punch cards were used, connected to each other in the form of a tape. The wooden pins of the "reading device" of the machine, by the location of the holes in the punched card, determined which threads should be raised and which ones should be lowered to obtain the desired pattern.

In 1890, in the United States, inventor Herman Hollerith developed an electromechanical calculating machine - a tabulator controlled by punched cards, was used to compile tables with the results of the US census. The Hollerith-founded tabulator firm later became International Business Machines Corporation (IBM).

In 1936, Alan Turing, a 25-year-old student at Cambridge University, published an article "On Computable Numbers", which considered a hypothetical device ("Turing machine") suitable for solving any solvable mathematical or logical problem - the prototype of a programmable computer.

In 1941, German engineer Konrad Zuse built a working Z3 computer that used the binary number system. The programs were recorded on punched tape.

In 1945, physicist John Mauchly and engineer Prosper Eckert built an all-electronic Eniak machine at the Graduate School of Technology at the University of Pennsylvania (USA). To set the program, it was necessary to manually set thousands of switches and plug hundreds of plugs into the sockets of the contact panel.

On June 1, 1945, a report was sent out by the Hungarian-American mathematician John von Neumann, A Preliminary Report on the Edvak Machine, containing the concept of storing computer instructions in its own internal memory.

On June 21, 1948, at the University of Manchester (Great Britain), on the Mark-1 machine, the world's first program stored in the memory of the machine was executed - the search for the largest factor of a given number.

In 1949, under the leadership of Maurice Wilkes, the Edsack computer was created. Edsak's designers introduced a system of mnemonic notation, where each machine instruction was represented by one capital letter, and automated the tuning of subroutines to a specific place in memory. Maurice Wilkes called the mnemonic diagram and subroutine library the assembly system - hence the word "assembler".

In 1949, in Philadelphia (USA), under the leadership of John Mauchly, "Short Code" was created - the first primitive interpreter of the programming language.

In 1951, American programmer Grace Hopper developed the first broadcasting program at the Remington Rand firm. Hopper called it a compiler.

In 1957, FORmula TRANslation (FORmula TRANslation) was born on the 20th floor of the IBM headquarters on Madison Avenue in New York. The development team was led by 30-year-old mathematician John Backus. Fortran is the first of the "true" high-level languages.

In 1972, 31-year-old systems programmer at Bell Labs, Dennis Ritchie, developed the C programming language.

In 1984, the French mathematician and saxophonist Philippe Kahn founds Borland International.

C was originally designed as a programming language for the Unix operating system.

It soon began to spread to practicing programmers. In the late 70s, C translators for Microcomputers were developed for the CP / M operating system.

After the appearance of the IBM PC, C compilers began to appear (there are now more than 20 of them for this computer).

In 1983, the American Standards Institute (ANSI) formed the X3J11 Technical Committee to create the C language standard. Borland's C ++ language, which appeared on the market, obeys most of the requirements of the standard.

At its core, C is a function language. C programming is carried out by writing functions and calling library functions. Most functions return some value that can be used in other operators.

Among the many advantages of the C language, the main ones should be noted:


Versatility (used on almost all existing computers);

Compactness and versatility of the code;

Speed ​​of program execution;

Language flexibility;

High structuredness.


Chapter 1. Basics of the C language

1.1. Alphabet

The language alphabet consists of the following characters:

Uppercase and lowercase Latin letters A-Z, a-z and the underscore character. Digits from 0 to 9. Special characters + - * / =>

The characters space, tab, line feed, carriage return are called spaces.

A C ++ program is a sequence of ACSII characters that represent its source text.

1.2. Basic C constructs

Consider a simple program for printing the phrase "Hello from the computer" on the screen

// program

printf ("Greetings from the computer");

Consider the structure of the program

C - program
# Preprocessor directives
Main
Operators
Function 1 ()
Operators
Function n ()
Operators
Descriptions
Assignments
Functions
Management
Empty

The #include command includes the stdio.h file in our program. The file contains information about the I / O functions.

A file named stdio.h contains I / O information.

The # symbol indicates that before translating the program, it is necessary to include functions from the stdio.h file in it - this is the so-called preprocessing processing, which performs some preprocessing of the program text before compiling.

The main () line contains the name of the function that the program always starts with. Empty brackets indicate that this is a function, but it has no parameters.

The // symbols are followed by comments (for one line), (symbols between / * and * / are also called comments).

Curly braces () mark the beginning and end of the body of a program or function. They are also used to combine multiple program statements into a block.

The line printf ("Greetings from the computer") contains the standard C print function. The character string enclosed in parentheses (argument) is the information passed to printf () from our main function main (). When the function is completed, control will return back to the original program. Symbol - denotes a line feed on a new line after printing.

Consider the following example - write a program for converting meters to centimeters.

printf ("% d M contains% d cm", I, J);

This program defines two integer variables I and J.

The scanf function has been introduced ("% d", & I); which allows you to enter a decimal number from the keyboard and assign the value to the variable I, then by the command J = 100 * I; calculation in progress 4.

Next line printf ("% d M contains% d cm", I, J); prints the phrase. The first% d (d is an integer variable) is replaced by the value I, the second% d is replaced by the value J.

The getch () function allows you to freeze the image on the screen and requires any character to complete the job.

Let's look at another example. Let's write a function and call it from our program.

printf ("Did you call me?");

printf ("I'm calling the supervisor function.");

printf ("Yes. See which student is asleep and wake them up.");

First, we describe the supervisor () function, and then call it in the main program by the supervisor (); command. As a result, we get a dialogue:

I am calling the supervisor function.

Did you call me?

Yes. See which student is asleep and wake them up.

1.3 I / O
To solve a problem in any problem area, it is necessary to write a program in which there should be commands that allow:
- allocate space for storing data;

Enter initial data;

Process the initial data according to the algorithm;

Display output.

C contains the functions needed to perform these actions. We will consider all the functions by examples and start with the I / O functions.

1.3.1. Conclusion

The output is carried out to the screen, printer, hard drive (floppy disks), port. Consider the display functions.

The printf function is for this purpose. Format: printf ([, arg1], ...).

The format is a double quoted string that is printed to the screen. Before printing, printf replaces all objects in the string according to the specifications of the argument. For example, printf ("% d M contains% d cm", I, J); The% d in the format string is the specification of the argument.

Argument specifications begin with a percent character (%) and a single letter denoting the data type.

The% d used in the spec indicates that some integer is expected. Here are a few other commonly used format specifications:

-% d integer;

-% u unsigned integer;

-% ld is a long integer;

-% p pointer value;

-% f floating point number;

-% e floating point number in exponential form;

-% c character;

-% s string;

-% x integer in hexadecimal format.

You can set the field width, for example,% 6d -field width 6.

The value will be printed shifted to the right (leading spaces) so that the total field width is 6.

For the format of real numbers, you can specify a fractional part, for example,% 8.4f - a field with a width of 8, decimal part 4.

At the end of the format string, you can put the characters:

line translation;.

f (format translation or screen clear)

(tab)

xhhh (insert ASCII character hhh, where hhh contains 1 to 3 hexadecimal digits)

For output, you can use the functions: puts and putchar.

The puts function prints the string to the screen. For instance:

puts ("Hello student");

The putchar function prints one character to the screen.

1.3.2 Input

Input in C is mainly done from the keyboard, from a file and from a port.

The scanf function is similar to printf. Its format is scanf ([, arg1], ...). Scanf uses the same format specifiers as printf. It should be noted that scanf has one peculiarity: the arguments following the format string must be addresses, not values ​​(this does not apply to character variables). Earlier in the examples, we saw that when entering an integer, the function was written as follows:

scanf ("% d", & a);

The & -address operation, which passes scanf addresses.

When entering multiple variables separated by commas, you can use the comma inside the format. Example:

scanf ("% d,% d", & a, & b);

Now you can enter, for example 23.56.

There are difficulties with entering a string of characters from several words - only data up to the first space will be entered. The gets function exists to solve this problem.

printf ("What's your name:");

printf ("Hello% s", name);

The gets function reads whatever is typed until Enter is pressed.

In C ++, I / O can be done not only using functions, but also using operations. Output operation>.

Display format: cout

Keyboard input format: cin

When using I / O operations, you must include the iostream.h file in your program.

I / O of several values ​​is possible (separated by a space).


1.4 Basic data types of the C language

1.4.1 Identifiers

The names that are assigned to constants, data types, variables, and functions are called identifiers. C has the following rules for creating identifiers: must begin with a letter (a ... z, A ... Z) or with an underscore (_), the rest of the identifier must be letters, underscores and / or numbers (0 ... 9 ).

1.4.2 Typed Constants

C uses constants, which are a name assigned to a value. The name identifier can be of any length, but the first 32 characters are recognized. The identifier begins with a Latin letter or an underscore character, subsequent characters can be numbers, Latin letters and underscores.

The C compiler treats uppercase and lowercase letters as distinct characters.

Typed constants are: integer, floating point, character constants, and character strings.

Constants are represented as whole decimal, octal, or hexadecimal numbers.

The description of constants begins with the const keyword, then the type and value, for example, const int Nalog = 2.

1.4.3 Variables

A variable is a named value whose value can change during program execution. The variable is of a specific type.


1.4.3.1 Integer types

Integers are represented by integer types. An integer type is a generic type whose representation depends on the operating system and processor type.

Let's consider the main types of integers:

Let's take a look at a simple example.

const int Nalog = 2;

Symma = Stavka * Nalog;

printf ("Symma naloga =% d", Symma);

The example declares one constant and two variables of an integer type.

1.4.3.2 Real types

A real type is used to store numbers with a fractional part.

There are the following basic types of real numbers in C ++:

Consider the following example.

const float Nalog = 0.7;

Symma = Stavka * Nalog;

printf ("Symma naloga =% 8.4f", Symma);

In this example, the real type is represented by the Symma variable.

1.4.3.3 Character types

The character type -Char is designed to hold one character, so its size is one byte.

Let's consider an example:

printf ("A =% c B =% c", A, B);

printf ("C =% c", C);

In this example, variable A is assigned the value 'D ^, variable B is assigned the value'! ^, And variable C is assigned the value of the character '* ^.

1.4.4 Data type string

To represent a character string in C, arrays of the char type are used.

Let's look at an example.

char A; / * length can be up to 256 characters * /

strcpy (A, "IBM PC Pentium");

strcpy (B, "Windows 95");

strcpy (C, ""); / * clear the variable * / printf ("A =% s", A);

printf ("B =% s", B);

printf ("C =% s", C);

In this example, there are three strings of characters A, B, C.

By command, for example, strcpy (A, "IBM PC Pentium"); line A contains the text IBM PC Pentium.

In addition to this example, you can use a character pointer to define strings. Example:

msg = "Hello student";

The asterisk in front of msg means that msg is a pointer to a character - i.e. msg can store the address of a symbol. However, this does not allocate memory for symbols.

The msg = "Hello, student" command assigns the starting address of this line - (the address of the P character) to the msg variable. Puts (msg) prints characters until it encounters a null character indicating the end of the line.

1.4.5 Structures

A set of related data located in memory is a structure. The following structures are considered in C: arrays, records and their combinations.

1.4.5.1 Arrays

A named collection of homogeneous data is called an array. Each element of the array is stored in a separate area of ​​memory and has its own number (starting from zero).

Let's look at an example.

B = 10; B = 20; B = 30;

printf ("B =% d", B);

printf ("B =% d", B);

printf ("B =% d", B);

printf ("B =% d", B);

In the considered example, an array B is defined, consisting of four integer elements. Array elements can be manipulated as with ordinary variables.

There are multidimensional arrays, for example:

Array A is a two-dimensional array (consists of four rows and three columns):

Array A is a four-dimensional array.

Let's consider an example of working with a two-dimensional array.

B = 1.2; B = 1.3;

printf ("B =% 4.2f B =% 4.2f B =% 4.2f", B, B, B);

printf ("B =% 4.2f B =% 4.2f B =% 4.2f", B, B, B);

1.4.5.2 Records

Unlike arrays, a record allows you to store data of various types. The writing starts after the keyword struct. Consider an example - the record stores information about students: last name, year of birth, group number.

typedef struct A (

strcpy (B.Fio, "Ivanow G.I."); B. God = 1977;

printf ("Fio =% s", B.Fio);

printf ("God =% d", B.God);

In the considered example, the record has the following structure:

struct A (/ * A record name) * /

char Fio; / * 1 record field * /

int God; / * 2 record field * /

The typedef key gives the structures a name.

The example can be rewritten as follows.

typedef struct (

strcpy (B.Fio, "Ivanow G.I.");

printf ("Fio =% s", B.Fio);

printf ("God =% d", B.God);

printf ("Gruppa =% d", B.Gruppa);

In the example, we considered one record, but in real life there cannot be one student in a group, so we can combine the array and the record and create an array of records. Let's look at an example.

typedef struct A (

WGruppa.God = 1977;

WGruppa.Gruppa = 384;

WGruppa.God = 1978;

WGruppa.Gruppa = 384;

printf ("Fio2 =% s", WGruppa.Fio);

printf ("God2 =% d", WGruppa.God);

printf ("Gruppa2 =% d", WGruppa.Gruppa);

We initially defined structure A, and then used it when declaring the WGruppa structure as an array of 12 structure B entries.

Now for addressing, we must specify the number of the array element and the name of the field.

There are options when one record contains another record, for example, adding an address to the student record discussed above. Example.

typedef struct Address (

char Street_Nd_Kw; );

typedef struct A (

Address D_addr; );

strcpy (WGruppa.Fio, "Ivanow G.I.");

WGruppa.God = 1977;

WGruppa.Gruppa = 384;

strcpy (WGruppa.D_addr.City, "Shadrinsk"); strcpy (WGruppa.D_addr.Street_Nd_Kw, "Lenina 10 kw.1");

strcpy (WGruppa.Fio, "Petrow R.G.");

WGruppa.God = 1978;

WGruppa.Gruppa = 384;

strcpy (WGruppa.D_addr.City, "Kataisk"); strcpy (WGruppa.D_addr.Street_Nd_Kw, "Akulowa 1 kw.2");

printf ("Fio1 =% s", WGruppa.Fio);

printf ("God1 =% d", WGruppa.God);

printf ("Gruppa1 =% d", WGruppa.Gruppa);

printf ("City =% s", WGruppa.D_addr.City);

printf ("Fio2 =% s", WGruppa.Fio);

printf ("God2 =% d", WGruppa.God);

printf ("Gruppa2 =% d", WGruppa.Gruppa);

printf ("City =% s", WGruppa.D_addr.City);

printf ("Street =% s", WGruppa.D_addr.Street_Nd_Kw);

1.4.6 Scope and lifetime of variables

According to their scope, C variables can be divided into three groups:

1. Variable, defined in all modules (files) of the program. Such a variable is defined using the extern keyword. This variable will be visible at all points in the program. Such a variable is global for the entire program.

2. A variable defined in one of the modules (file) before the texts of all functions. Such a variable will be global for this module, i.e. can be used at all points of this module.

3. The variable defined in the given function. This variable can only be used within this function. We will call this variable local.

According to their lifetime, all variables can be divided into two groups:

1.Variables living during the work of the program.

2. Variables destroyed after exiting the function.

Global variables are of the first type in terms of lifetime. Local variables are destroyed upon exiting the function. In the case when we want to make a local variable long-lived, the word static is used. Local variables of this type live from the moment of the first call of the function until the end of the program. However, in terms of visibility, these variables remain local. Static int i = 0; Means that the variable is initialized to zero at the first entry into the function, but on subsequent entries into the function, its value is retained depending on the actions that were performed on it.

Modern C compilers translate the program in such a way as to optimize its performance as much as possible. One optimization technique is to store variables, whenever possible, in registers instead of memory locations. In those cases when you want to prohibit that a given variable is stored in registers, the volatile modifier is used. Such a need may arise if it is assumed that a variable can change as a result of external influences (for example, interruptions).

And one last remark. Dynamically allocated memory, wherever you allocate it, lives until you free it.

1.5 Basic operators

Assignment operation.

The most common operation is assignment, for example c = a / b. In C, assignment is denoted by an equal sign =, whereby the value to the right of the equal sign is assigned to the variable to the left. It is possible to use sequential assignments as well, for example: c = a = b.

Arithmetic operators.

The following groups of arithmetic operations are performed in C:

1.Binary: addition (+), subtraction (-), multiplication (*), division (/), integer division (%) (for int type, getting the remainder).

2.Unary: unary plus (+), unary minus (-), addressing (&), indirect addressing (*), determining the size of the memory type (sizeof).

3.Logical: and (&&), or (!!), not (! =).

4.Relationships:

a) is equal (==), not equal (!>);

b) less than (), less than or equal to (=);

5. Increments (++) and decrements (-). For example, i ++ means i = i + 1, and i-- means i = i-1.

6. Bitwise operations - allows you to perform operations on bits.

7. Combined operations. In Turbo-C, there are abbreviations for writing expressions containing numerous operations:

a = a + b; shortened to a + = b;

a = a - b; is reduced to a - = b;

a = a * b; shortened to a * = b;

a = a / b; is reduced to a / = b;

a = a% b; is reduced to a% = b;

8.Address operations:

1. The operation of determining the address (&) 2. The operation of addressing the address (*).

The & operation returns the address of the given variable; if X is a variable of type int, then & X is the (memory location) address of that variable. On the other hand, if msg is a pointer to char, then * msg is the character pointed to by msg. Let's consider an example:

msg = "Hello";

printf ("X =% d & X =% p", X, & X);

printf ("* msg =% c msg =% p", * msg, msg);

When printed in the first function, two values ​​are printed: the value X 7 and the address X (assigned by the compiler). The second function also prints two values: the character pointed to by msg (P), and the value msg, which is the address of that character (also assigned by the compiler).

The precedence of operations in C corresponds to the precedence of operations in mathematics.

The comma operator.

The comma operator is used to organize multiple expressions within parentheses. The expression within parentheses is evaluated from left to right, and the entire expression evaluates to the value that was evaluated last. For instance:

(X = Y, Y = getch ())

assigns the X value to Y, then reads the character entered from the keyboard, and stores it in Y. The result of the whole expression, as a result, will be the value of the character entered from the keyboard.

Control operators.

The If ... operator makes it possible, depending on the condition, to execute this or that branch of the program. The syntax for the operator is as follows:

If condition expression1 else expression2;

The condition must result in a logical true or false value. Expression1 will be executed if the condition is true. Expression2 will be executed if the condition is false.

There is an abbreviated version of the operator:

If condition expression1

Example. Determine if the entered number is a day of the week, i.e. whether the number is in the range from 1 to 7.

printf ("Error% d", A);

else printf ("OK% d", A);

The condition expression (A 7) will return TRUE if A 7 is executed - in this case the printf ("Error", A); branch is executed, otherwise the printf ("OK", A); branch is executed.

There is another variant of writing the If statement ... Example:

y = (t> 0)? t * 10: t-10; / * if t> 0 y = t * 10 else y = t-10; * /

printf ("OK% d", y);

In this variant, the type of the operator is shown in the comments.

The switch ... case operator is used when it is necessary to analyze a variable and, depending on its value, perform certain actions. Let's look at an example. Letters of the Latin alphabet are entered from the keyboard. Perform certain actions depending on the letter.

case "c": printf ("smoll% c", A); break; / * exit the block * /

case "G": printf ("big% c", A);

default: printf ("Error% c", A);

In this example, if a character c is entered, then printf ("smoll% c", A); is executed, if an uppercase F or G is entered, then printf ("big% c", A); is executed if not one of the considered characters is not entered, then printf ("Error% c", A); is executed.

To repeat a set of commands multiple times, you can use the do ... while statement. Let's look at an example.

printf ("Zifra?");

printf ("Error% d", A);

) while (! (A == 9));

printf ("OK% d", A);

A number is entered from the keyboard. The printf ("Error% d", A); statement is executed. Next comes the analysis - whether the number is 9 or not, if not, the loop body is executed again:

printf ("Zifra?");

printf ("Error% d", A).

If the number is 9, then printf ("OK% d", A) is executed; and the cycle ends.

The main feature of the do ... while operator is the fact that the loop body enclosed between the do and while statements is executed at least once, i.e. first, the body of the loop is executed, and then the condition is analyzed.

Thus, the meaning of the operator under consideration is as follows: "Execute the body of the loop until the condition is true."

The while ... operator, unlike do ... while, first analyzes the condition and then executes the body of the loop.

printf ("Zifra?");

printf ("Error% d", A);

printf ("OK% d", A);

In this example, the variable A is initialized: = 0 ;. This is done because at the beginning it is analyzed whether it is 9 or not. If not, then the body of the loop is executed. The meaning of the operator in question is as follows:

"While the condition is true, execute the body of the cycle."

The for ... operator is used when it is known how many times the body of the loop needs to be executed, but this operator is much more flexible than Pascal. Let's look at an example.

printf ("Zifra% d", A);

In this example, A stores the state of the loop counter. Initially A: = 1. The printf statement ("Zifra% d", A) is executed. Further, the value of A is increased by one. Analysis in progress A

In the following example, consider a variant of the for ... operator, when the initial value of the variable is greater than the final value, and the variable decreases by one during the loop.

for (A = 5; A> = 1; A--) / * A-- means A = A-1 * /

printf ("Zifra% d", A);

There are many modifications to the for ... statement, for example:

Empty statement - for time delay:

; / * empty operator * /

Using a different step:

Changing variables:

Consider an example in which two variables are initialized and each of which is changed after iterating through the loop:

The goto statement allows you to transfer control to any line of the program. A label is used for this purpose. Example.

label_1: / * label * / printf ("?");

if (A! = "y") goto label_1; )

To interrupt the loop on some condition, you can use the break statement. Example.

i (A == "y") break;

The Continue statement is used to interrupt the loop iteration and go to the next iteration. Example.

if (A == "y") continue;

printf ("% c works", A);

The return () and exit () statements are also used to interrupt the program.

1.6. Preprocessor

The preprocessor of the C language allows, before starting the translation, to include in the program fragments of programs written separately from the main one.

#Define directive.

The #define directive can appear anywhere in the program, and the definition it gives is valid from place to the end of the program.

#define OTWET TRI * TRI

#define OT printf ("ANSWER is% d.", OTWET)

#define jd cin >> C;

After executing the program, you get:

ANSWER is 9

In the first line of the program, TRI is a macro definition and it is equal to 3, where 3 is the replacement string.

In the second line, the macro OTWET has a replacement string TRI * TRI, and so on. Each line has three parts. The first is the #define directive, followed by the macro definition. Macros must not contain spaces inside them. Finally, there is a string (called a "replacement string") that represents the macro. When the preprocessor finds one of the macros in the program, it replaces it with a replacement string. This process of going from the macro definition to the final replacement string is called "macro expansion".

#Include directive.

When the preprocessor "recognizes" the #include directive, it looks for the next filename and includes it in the current program. The directive comes in two forms:

#include filename in angle brackets

#include "my.h" filename in double quotes

The angle brackets tell the preprocessor to look for a file in one or more of the standard system directories. The quotes tell him to look in the working directory first and then look in the "standard" places.

Directives: #undef, #ifdef, #else, #endif

These directives allow you to suspend earlier definitions.

The #undef directive overrides the most recent definition of a named macro.

#undef TRI / * TRI is now undefined * /

#define F 10 / * F redefined as 10 * /

#undef F / * F is 5 again * /

#undef F / * F is now undefined * /

Let's look at another example.

#include "otw.h" / * will execute if OTW is defined * /

#include "w.h" / * will be executed if OTW is not defined * /

The ifdef directive says that if a subsequent OTW identifier is determined by the preprocessor, then all subsequent directives are executed up to the first occurrence of #else or #endif. When there is #else in the program, the program #else to #endif will run if no identifier is specified.

1.7 Programs. Functions

As we discussed earlier, a C program has a root segment starting with preprocessor directives and the main keyword.

Frequently used sections of the program are highlighted in functions. Each function also starts with preprocessor directives and a name and parentheses ().

Let's look at an example of a program for drawing a staircase.

printf ("| ---- |");

printf ("| ---- |");

printf ("| ---- |");

Now let's write this program using the Lestniza function.

printf ("| ---- |");

As you can see from the program, the function is called three times. To overcome this shortcoming, we will rework the program and introduce formal and factual arguments:

Lestniza (int B) / * B is a formal argument * /

printf ("| ---- |");

Lestniza (3); / * 3 -actual argument * /

In this function, B is the formal argument (the final value of the for to statement). To assign a specific value to it, the actual argument is used, which is passed to the function when it is called in the main program.

If several parameters are passed to a function, then they must be passed in the order in which they are written in the function.

Consider a function that returns its value using the example of squaring a number.

float Kwadrat (float A)

printf ("Kwadrat =% 8.2f", Kwadrat (B));

As you can see from the example - the name of the function is Kwadrat - it calculates the square of a number. On the line printf ("Kwadrat =% 8.2f", Kwadrat (B)); this function is called - the value (entered number) is supplied to the input, and as a result we get the result - the square of the number, which is returned to the program by the return command.

Let's consider another option for working with a function that returns a value without a return command.

Kwadrat (float A, float * B)

printf ("Kwadrat =% 8.2f", D);

1.8. Pointers

A pointer is a variable that contains the address of the data, not its value. The pointer is used:

1. For communication of independent structures with each other.

2. For dynamic memory allocation.

3. To access various elements of the structure.

Consider the following program:

printf ("Direct value Z:% d", Z);

printf ("Z value obtained through a pointer:% d", * Y);

printf ("Address Z by getting address:% p", & Z);

printf ("Address Z through a pointer:% p", Y);

In this example, Y is a pointer to an integer variable and contains its address. In turn, & allows you to get the address at which the value of the Z variable is located. In this program:

The address of the variable Z is assigned to Y;

An integer value of 100 is assigned to Z;

The & operator, allows you to get the address,

on which the Z value is placed.

The result of the program:

Direct Z-value: 100

Z value obtained through a pointer: 100

Address Z by receiving address: 85B3: 0FDC

Z address via pointer: 85B3: 0FDC

Pointers are also used for optimal memory allocation.

Let's consider an example of a pointer to a number of type char.

char * str; / * pointer to character variable * /

str = (char *) malloc (10);

strcpy (str, "Hello");

printf ("String is% s", str);

First, by the command char * str; type str has been created, which is a pointer to a variable of type char (* stands for "pointer"). By command str = (char *) malloc (10); allocate 10 bytes of memory for the str variable (string type). By command strcpy (str, "Hello"); carried out - "write to the memory area pointed to by str, the character string" Hello ". On the command printf (" String is% s ", str); carried out" print on the screen what str points to. Free command (str); frees the memory pointed to by str.

Let's look at a more complex example of accessing a record using a pointer.

); / * end of record * /

struct Student * A;

if ((A = (Student *) malloc (sizeof (Student))) == NULL)

printf ("Out of memory");

strcpy (A.Fio, "Ivanov");

printf ("Fio1% s Gruppa% d", A.Fio, A.Gruppa);

strcpy (A.Fio, "Petrow");

printf ("Fio2% s Gruppa% d", A.Fio, A.Gruppa);

A pointer can also be used to get an indirect pointer to a structure.

Let poit be a pointer to a structure and that elem is an element defined by the structure pattern. Then point-> elem defines the element to be referenced. Let's look at the previous example.

struct Student (/ * Student record * /

char Fio; / * record field Fio * /

int Gruppa; / * Gruppa record field * /

); / * end of record * /

Now we can access the fields of the structure in several ways. Equivalent calls:

Student.Gruppa = 236;

poin-> Gruppa = 236;

Note one important feature of C pointers. The translator automatically takes into account the type of the pointer in arithmetic operations with it. For example, if i is a pointer to an integer (i.e., two-byte) variable, then an action like i ++ means that the pointer receives not one but two bytes increment, i.e. will point to the next variable or element in the array. For this reason, a pointer can be used instead of array indices. For example, if A is a pointer to an array of integer type, then instead of A [i] you can write * (A + i). Moreover, using pointers instead of indices allows the compiler to write more compact and faster code.

1.9 Pointers and Functions

Pointers can also be used as formal parameters to a function. Let's look at an example.

The swap function declares two formal parameters x and y as pointers to int data. This means that the swap function works with the addresses of integer variables (not their values). Therefore, the data will be processed, the addresses of which were passed to the function during the call to it. The main () function calls swap.

swap (int * x, int * y)

wr = * x; * x = * y; * y = wr;

printf ("It was: i =% d, j =% d", i, j);

printf ("Now: i =% d, j =% d", i, j);

After the execution of the program, the values ​​of i and j are swapped. It should be noted that although pointers save memory, they use much more CPU time.

Thus, the main elements of the C language are considered.

1.10 Files

A file is a collection of data recorded on some medium. You can create a file, write data to it, erase data, update data, add data. File I / O is performed using direct or sequential access methods.

Let's take a look at the sequential access mode first.

I / O is buffered. This means that the program writes and reads to the buffer; data exchange between the buffer and the file occurs when the buffer is full, or the file is closed, or before exiting the program.

printf ("Source file");

printf ("Output file");

if ((in = fopen (n1, "rt")) == NULL)

printf ("Can't open source file"); return 1;

if ((out = fopen (n2, "wt")) == NULL)

printf ("Can't open the output file"); return 1;

while (! feof (in))

fputc (fgetc (in), out);

String FILE * in, * out; defines a pointer to two files. File name m.b. any - in our case, in is the source file, out is the output.

In the next line char n1, n2; define two variables n1 and n2 to store filenames. The next four lines allow you to enter the names of the input and output file and assign those names to the variables n1 and n2. Before you can start working with a file, it must be open. For this there is a function fopen () in which the first parameter contains the file name, and the second - the type of work, for example "rt" - read the file.

The command in = fopen (n1, "rt" will open the file stored in the variable n1 for reading, and the program will return the in pointer to this file, which (the pointer) we will use when reading symbols from the file. If the file does not exist then fp will be NULL, fprintf (stderr, "Can't open output file"); return 1; will be executed and the program will exit.

The function out = fopen works similarly (n2, "wt", only now out is the output file, and the type of work "wt" is writing to the file).

This command creates a file with the name written in the n2 variable.

Reading from a file is done by calling fgetc (in). One character is read from the file associated with the in pointer.

Fputc (fgetc (in), out); the character read is written to the file out. To read information from the entire file, use the while (! Feof (in)) construction.

fputc (fgetc (in), out) ;.

The feof (in) function returns a nonzero value if it is in the end position, and zero otherwise. Until zero is encountered, data from the source file is read and written to the output.

The file is closed when the fclose () function is called. If the file was opened for writing, the contents of the buffer associated with this file are output. The link between the pointer and the file is broken.

Likewise, fgetc (string, n, fp) reads a string from the file associated with fp and places it in string. Characters are read until the character "" is received, or until the file is exhausted, or until (n-1) characters have been read.

Direct access mode is more flexible because allows you to directly access any record in the file. The minimum record for a direct access file is a byte. Below we will consider the case of a direct access file with a write equal to a byte. These files are called binary files. Direct access files are indispensable when writing programs that must work with large amounts of information stored on external devices. The processing of the DBMS is based on direct access files.

Let us briefly outline the main provisions of working with direct access files.

one). Each entry in the direct access file is numbered. Records are numbered from 0 to N-1, where N is the number of records in the file. For a binary file, N is the same as the length of the file in bytes. For an open file, one of the records is current - they say that the pointer is set to this record. You can move the pointer using the lseek function.

2). When opening (or creating a file), the pointer is automatically positioned to the beginning (entry 0). When performing read or write operations, the pointer automatically moves past the last read (written) record.

3). You can change the size of the file (increase or decrease) using the chsize function. As the file size grows, entries filled with 0 codes are added to it.

Below is a program that demonstrates working with files.

int h; / * file descriptor to create * /

char * s = "This line will be placed in the file";

char buf; / * buffer to read from file * /

Fmode = O_BINARY; / * working with binaries * /

if ((h = creat ("proba.txt", S_IREAD | S_IWRITE)) == - 1) / * create file * /

printf ("Failed to open file!");

write (h, s, strlen (s)); / * write the string s to the file * /

lseek (h, 4, SEEK_SET); / * fourth byte from the beginning of the file * /

buf = 0; / * mark the end of the line * /

close (h); / * close file * /

printf ("% s", buf); / * print the line read * /

Our program is fully commented on, so we provide a fairly brief explanation. The program creates a direct access file and writes a sequence of bytes (string) there. Further, there is a direct reference to the substring of this string directly in the file. When parsing the text of the program, let's draw readers to some points:

1. Handling file creation error. Indeed, opening a file may not be successful and a good program should handle such situations.

2. If the file is successfully opened, it is assigned a descriptor (a unique number), which can then be used to access the file.

3. Finally, do not forget that a string will only become a string when there is a code at the end

Top related articles