How To Add To A File

Table of contents:

How To Add To A File
How To Add To A File

Video: How To Add To A File

Video: How To Add To A File
Video: Windows 10 - Create a Folder - How to Make New File Folders on Your Laptop Computer Files u0026 Folders 2024, May
Anonim

Often when the software is running, it is required to enter the resulting data into an existing file. Moreover, it is necessary to add the file in such a way that the rest of the data stored there remains unchanged. This task can be easily solved using the functions of the C programming language. The easiest way to add data to a file is to use special attributes of the standard file function. With their help, you can open and add data to a file several times during the program's operation.

How to add to a file
How to add to a file

Necessary

C programming environment

Instructions

Step 1

Functions for working with files and outputting data to them when programming in C are in a special library. Connect them to your program. To do this, before writing the code, specify the header file for this library. Enter the line #include "stdio.h".

Step 2

In the text of your program, create a pointer to the file descriptor. To do this, write a line in the program code like: FILE * pFile, where pFile is the name of the created pointer.

Step 3

Open the file where you need to add data. Use the following function: pFile = fopen ("NameFile.txt", "a"). Here NameFile.txt is the name of the file. The second parameter, the symbol of the Latin alphabet, "a" sets the file opening mode with the ability to add data to it.

Step 4

If the file to which you need to add values is not in the same directory where your program is running, then along with the file name specify the full path to it on the hard disk. To do this, change the line in the first parameter. For example, the path to a file located in the root directory of the D drive is specified by the entry: "D: NameFile.txt".

Step 5

Add the data you want to the open file. For this, it is better to use the overloaded function fprintf (pFile, Added data:% s

, datStr). The first pFile parameter in this function specifies the file descriptor to be added. Next comes the line that is output to the file in its entirety, except for special characters.

Step 6

The characters after the "%" sign indicate the types of output data. So, the expression "% s" means that the third parameter of the function is a string variable. To output to a file by a variable of type int, put the expression "% d", to output the address of the pointer - "% p". For line feed after data recording, the symbol “

. Thus, the next data entered into the file will be written on a new line.

Step 7

After displaying the data you need, close the file by its descriptor using the fclose (pFile) command. Then save the program, compile and run it. The specified data will be added to the file.

Recommended: