With files and strings examples. Input from file and output to file

Text files

Let's look at working with a text file in C using an example. Create a text file on drive C named TextFile.txt. Type the following lines in this file:

String_1 123 String_11, 456
String_2
String_3

Save the file.

And this is the code for a C program that opens our file and reads lines from it:

/* *Author: @author Subbotin B.P..h> #include #define LEN 50 int main(void) ( puts("Text file operations"); char cArray; FILE *pTextFile = fopen("C:\\TextFile.txt", "r"); if(pTextFile == NULL) ( puts("Problems"); return EXIT_FAILURE; ) while(fgets(cArray, LEN, pTextFile) != NULL) ( printf("%s", cArray); ) fclose(pTextFile); return EXIT_SUCCESS;

To open a text file in C, use the fopen function:

FILE *pTextFile = fopen("C:\\TextFile.txt", "r");

The first argument to the fopen function points to a file, and the second says that the file is open for reading from it.

We read the lines using the fgets function:

fgets(cArray, LEN, pTextFile);

The first argument of the fgets function points to a character array in which the received strings will be stored, the second argument is the maximum number of characters to read, and the third is our file.

After finishing working with the file, you need to close it:

fclose(pTextFile);

We get:

Russian letters also appear in the lines.

By the way, I made this program in Eclipse. You can see how to work with C/C++ in Eclipse.

So, we opened and read data from a text file.

Now we will learn how to programmatically create a text file and write data to it.

/* Author: @author Subbotin B.P..h> #include int main(void) ( FILE *pTextFile = fopen("C:\\TextFileW.txt", "w"); char *cString = "This is a string"; char cNewLine = "\n"; int nVal = 123 ; if(pTextFile == NULL) ( puts("Problems"); return EXIT_FAILURE; ) fprintf(pTextFile, "%s%c", cString, cNewLine); ; )

Create a text file to write data to:

FILE *pTextFile = fopen("C:\\TextFileW.txt", "w");

if the file already exists, it will be opened and all data from it will be deleted.

The C-string cString and the number nVal are written by the program to a text file. cNewLine is simply a new line.

We write data to a text file using the fprintf function:

fprintf(pTextFile, "%s%c", cString, cNewLine);

the first argument here is our file, the second is the format string, the third or more is the number of arguments required for this format.

For ease of access, information in storage devices is stored in the form of files.

A file is a named area of ​​external memory allocated for storing an array of data. The data contained in the files is of a very diverse nature: programs in algorithmic or machine language; initial data for program operation or program execution results; free texts; graphic images, etc.

Directory (folder, directory) - a named collection of bytes on a storage medium containing the names of subdirectories and files, used in the file system to simplify the organization of files.

File system called the functional part of the operating system that performs operations on files. Examples of file systems are FAT (FAT - File Allocation Table), NTFS, UDF (used on CDs).

There are three main versions of FAT: FAT12, FAT16 and FAT32. They differ in the bit depth of records in the disk structure, i.e. the number of bits allocated to store the cluster number. FAT12 is used mainly for floppy disks (up to 4 KB), FAT16 - for small-capacity disks, FAT32 - for high-capacity FLASH drives (up to 32 GB).

Let's look at the structure of the file system using FAT32 as an example.

FAT32 file structure

External memory devices in the FAT32 system have block addressing rather than byte addressing. Information is written to an external memory device in blocks or sectors.

A sector is the minimum addressable unit of information storage on external storage devices. Typically, the sector size is fixed at 512 bytes. To increase the address space of external memory devices, sectors are combined into groups called clusters.

A cluster is a union of several sectors, which can be considered as an independent unit with certain properties. The main property of a cluster is its size, measured in the number of sectors or number of bytes.

The FAT32 file system has the following structure.

The clusters used for writing files are numbered starting from 2. As a rule, cluster No. 2 is used by the root directory, and starting from cluster No. 3 the data array is stored. Sectors used to store information above the root directory are not clustered.
The minimum file size required on disk corresponds to 1 cluster.

The boot sector begins with the following information:

  • EB 58 90 – unconditional jump and signature;
  • 4D 53 44 4F 53 35 2E 30 MSDOS5.0;
  • 00 02 – number of bytes in the sector (usually 512);
  • 1 byte – number of sectors in the cluster;
  • 2 bytes – number of reserve sectors.

In addition, the boot sector contains the following important information:

  • 0x10 (1 byte) – number of FAT tables (usually 2);
  • 0x20 (4 bytes) – number of sectors on the disk;
  • 0x2С (4 bytes) – cluster number of the root directory;
  • 0x47 (11 bytes) – volume label;
  • 0x1FE (2 bytes) – boot sector signature (55 AA).

The file system information sector contains:

  • 0x00 (4 bytes) – signature (52 52 61 41);
  • 0x1E4 (4 bytes) – signature (72 72 41 61);
  • 0x1E8 (4 bytes) – number of free clusters, -1 if unknown;
  • 0x1EC (4 bytes) – number of the last recorded cluster;
  • 0x1FE (2 bytes) – signature (55 AA).

The FAT table contains information about the state of each cluster on the disk. The lower 2 bytes of the FAT table store F8 FF FF 0F FF FF FF FF (which corresponds to the state of clusters 0 and 1, which are physically absent). Next, the state of each cluster contains the number of the cluster in which the current file continues or the following information:

  • 00 00 00 00 – cluster is free;
  • FF FF FF 0F – end of the current file.
  • 8 bytes – file name;
  • 3 bytes – file extension;

The root directory contains a set of 32-bit information records about each file, containing the following information:

When working with long file names (including Russian names), the file name is encoded using the UTF-16 encoding system. In this case, 2 bytes are allocated for encoding each character. In this case, the file name is written in the following structure:

  • 1 sequence byte;
  • 10 bytes contain the lower 5 characters of the file name;
  • 1 byte attribute;
  • 1 byte reserved;
  • 1 byte – DOS name checksum;
  • 12 bytes contain the lower 3 characters of the file name;
  • 2 bytes – number of the first cluster;
  • the remaining characters of the long name.

Working with files in C language

To the programmer, an open file is represented as a sequence of data being read or written. When a file is opened, it is associated with I/O stream. Output information is written to the stream, input information is read from the stream.

When a stream is opened for I/O, it is associated with a standard FILE structure, which is defined in stdio.h. The FILE structure contains the necessary information about the file.

Opening a file is done using the fopen() function, which returns a pointer to a structure of type FILE that can be used for subsequent operations on the file.

FILE *fopen(name, type);


name – name of the file to open (including path),
type is a pointer to a string of characters that define how the file is accessed:
  • "r" - open the file for reading (the file must exist);
  • "w" - open an empty file for writing; if the file exists, its contents are lost;
  • "a" - open the file for writing to the end (for appending); the file is created if it does not exist;
  • "r+" - open the file for reading and writing (the file must exist);
  • "w+" - open an empty file for reading and writing; if the file exists, its contents are lost;
  • "a+" - open the file for reading and appending; if the file does not exist, then it is created.

The return value is a pointer to the open stream. If an error is encountered, NULL is returned.

The fclose() function closes the stream or streams associated with files opened using the fopen() function. The stream to be closed is determined by the argument of the fclose() function.

Return value: value 0 if the stream was closed successfully; constant EOF if an error occurred.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include
int main() (
FILE *fp;
char name = "my.txt" ;
if ((fp = fopen(name, "r" )) == NULL )
{
printf( "Failed to open file");
getchar();
return 0;
}
// succeeded in opening the file
... // required actions on data
fclose(fp);
getchar();
return 0;
}

Reading a character from a file:

char fgetc(stream);


The function argument is a pointer to a stream of type FILE. The function returns the code of the read character. If the end of the file is reached or an error occurs, the constant EOF is returned.

Writing a symbol to a file:

fputc(char, stream);

The function's arguments are a character and a pointer to a stream of type FILE. The function returns the code of the read character.

The fscanf() and fprintf() functions are similar to the scanf() and printf() functions, but work with data files, and have a file pointer as their first argument.

fscanf(stream, "InputFormat", arguments);

To the programmer, an open file is represented as a sequence of data being read or written. When a file is opened, it is associated with I/O stream . Output information is written to the stream, input information is read from the stream.

When a stream is opened for I/O, it is associated with a standard FILE structure, which is defined in stdio.h. The FILE structure contains the necessary information about the file.

Opening a file is done using the fopen() function, which returns a pointer to a structure of type FILE that can be used for subsequent operations on the file.

FILE *fopen(name, type);

name – name of the file to open (including path),
type - pointer to a string of characters defining how the file is accessed:

· "r" - open the file for reading (the file must exist);

· "w" - open an empty file for writing; if the file exists, its contents are lost;

· "a" - open the file for writing to the end (for appending); the file is created if it does not exist;

· "r+" - open the file for reading and writing (the file must exist);

· "w+" - open an empty file for reading and writing; if the file exists, its contents are lost;

· "a+" - open the file for reading and appending; if the file does not exist, then it is created.

The return value is a pointer to the open stream. If an error is detected, NULL is returned.

The fclose() function closes the stream or streams associated with files opened using the fopen() function. The stream to be closed is determined by the argument of the fclose() function.

Return value: value 0 if the stream was closed successfully; constant EOF if an error occurred.

#include
int main()

char name="my.txt";

if(fp = fopen(name, "r")!=NULL)

// was it possible to open the file?
... // required actions on data

else printf("Failed to open file");

Reading a character from a file:

char fgetc(stream);

The function argument is a pointer to a stream of type FILE. The function returns the code of the read character. If the end of the file is reached or an error occurs, the constant EOF is returned.
Writing a symbol to a file:

fputc(char, stream);

The function's arguments are a character and a pointer to a stream of type FILE. The function returns the code of the read character.

The fscanf() and fprintf() functions are similar to the scanf() and printf() functions, but work with data files, and have a pointer to the file as their first argument.

fscanf(stream, "Input Format", arguments);
fprintf(stream, "Output Format", arguments);

The fgets() and fputs() functions are designed for string input/output; they are analogous to the gets() and puts() functions for working with files.

fgets(Pointer To Line, Number Of Characters, stream);

Characters are read from the stream until a newline character "\n" is read, which is included in the string, or until the stream ends EOF or the maximum number of characters has been read. The result is placed in a string pointer and ends with the null character "\0". The function returns the address of the string.

fputs(Pointer To String, stream);

Copies a string to the stream from the current position. The terminating null character is not copied.
Example Enter the number and save it in the s1.txt file. Read the number from the file s1.txt, increase it by 3 and save it in the file s2.txt.

We have already learned how to write information into a text file. – If you haven’t learned how, see the previous article. It is told and described in detail

But what if the file already exists and we need to read information from it for processing? Fortunately, this is also quite simple. Let me remind you that there are several options for implementing this task; I have described only one of them. The one described is the one that for some reason seems to me personally the easiest to understand.

#include

int main()
{
char s1 //The variable will read the string
ifstream in (“C:\\\FromC\\myfile.txt” ); //Open the file to read information
in >>s1 ; //read the line
in.close() // Closing the file

cout<Output the value s1 to the screen
return 0 ;
}

Here is the simplest program to read the first line from a text file located along the path
C:\\\FromC\\myfile.txt –
Since this is a continuation of the previous article, I decided to use the file that we created there. There probably shouldn't be any difficulties with this.
But let's get back to the code. First we open the file to read information from it, for this we use the command ifstream in brackets we indicate either the file name or the path to the file, as I did. (“C:\\\FromC\\myfile.txt” );
When we opened a file to read something from it, we declared one variable like char –
char s1
Now all we have to do is assign the variable the value of the string from the file. We do this as a team in
Pay attention to the angle brackets in >>
Actually, as can be seen from the comments to the program code, in order for the variable to assign the read value, we must write it after in >>
in >>s1 ;

This does not seem to be a particularly difficult task, especially if you have already perfectly mastered and learned to use the material from the previous article - everything is absolutely the same, only 2 commands are different

Creating a file and writing C++ information to it

ofstream out ( File name );
out<< (String to be written);
out.close();
=============================

Reading text from a file and printing text to screen in C++

ifstream in (File name );
in>> (Reading the line);
in.close();(Close the file)
============================
Let's write a simple program that will read text input from the keyboard and write it to a file:

#include
#include

int main()
{
\\ 3 future lines
clrscsr(); // Clearing the screen

cout<<“Wwedi pervuu stroku” ; cin >>a ; endl ;
cout<<“Wwedi wtoruu stroku” ; cin >>b ; endl ;
cout<<“Wwedi tretuu stroku” ; cin >>c ; endl ;
clrscr(); //

/*Start working with the file*/
ofstream out (“C:\\\FromC\\myfile.txt” ); //Opening a file for writing
out<Write down the first line
out<Write the second line
out<Write down the third line
out.close(); // Closing the file

//Reset variables to zero

for (int i =0 ;i<=255 ;i ++)
(a =*“” ; b =*“” ; c =*“” ;)


ifstream in(“C:\\\FromC\\myfile.txt” );
in >>a >>b >>c ; //We read each new line into a new variable
in.close(); // Closing the file

/* */

for (i =0 ;a !=*“” ;i ++)
{
if (i >sizeof(a )) break ;
cout<

}
cout<<“\n” ; \\

/* */


{
if (i >sizeof(b)) break ;
cout<
}
cout<<“\n” ; \\ Moved the cursor to a new line

/* */

for (i =0 ;с !=*“” ;i ++)
{
if (i >sizeof(c )) break ;
cout<<с ;
}

return 0 ;
}
===================

In the examples above there is one such HUGE flaw. If we try to enter a line containing spaces, the program will not work as we need. Probably, not only I, but also many other people came across this error. Therefore, I leave the incorrect code so that you can see what you might encounter.

Since there are no books at home, I again began to scour the Internet and found a lot of all sorts of sophisticated nonsense. But somehow I found a solution to my problem.
It helped that I read that cout supports his methods. And on the Internet all advice goes towards using the function getline Luckily for me, I found out how to use this function very quickly and then used it in the code.
In general, it’s worth mentioning and describing this function, but so far I don’t really understand it, I just understand that it needs to be used and I understand how, so I’ll give a more correct example of our program being developed:

#include
#include

int main()
{
char a,b,c; \\ 3 future lines
clrscsr(); // Clearing the screen

/* Enter values ​​for variables*/

cout<<“Wwedi pervuu stroku” ; cin.getline(a,sizeof(a)); endl ;
cout<<“Wwedi wtoruu stroku” ; cin.getline(a,sizeof(b)); endl ;
cout<<“Wwedi tretuu stroku” ; cin.getline(a,sizeof(c)); endl ;
clrscr(); //After entering the values, the screen was cleared

/*Start working with the file*/
ofstream out (“C:\\\FromC\\myfile.txt”); // Opening a file for writing
out<
Write down the first line
out<Write the second line
out<Write down the third line
out.close(); // Closing the file

//Reset variables to zero

for (int i =0 ;i<=255 ;i ++)
(a =*“” ; b =*“” ; c=*“” ;)

/*Continue working with the file*/

if stream in (“C:\\\FromC\\myfile.txt” );
in.getline(a,sizeof(a));// A
in.getline(b,sizeof(b));// Reading a line into a variable b
in.getline(c,sizeof(c)); // Reading a line into a variable c
in.close(); // Closing the file

/* We read the first line character by character and display it on the screen */

for (i =0 ;a !=*“” ;i++)
{
if (i >sizeof(a )) break ;
cout<

}
cout<<“\n” ; \\ Moved the cursor to a new line

/* We read the second line character by character and display it on the screen */

for (i =0 ;b !=*“” ;i ++)
{
if (i >sizeof(b)) break ;
cout<
}
cout<<“\n” ; \\ Moved the cursor to a new line

/* We read the third line character by character and display it on the screen */

for (i =0 ;с !=*“” ;i++)
{
if (i>sizeof (c )) break ;
cout<<с[i];
}

getch(); \\Waiting for the Enter key to be pressed
return 0 ;
}
===================

This material describes an example of character-by-character reading of information. Since I did not describe working with variables like char, then beginners may experience some inconvenience in understanding the code. I just didn't know what type char has some peculiarities and thought everything was simpler. Therefore, some incomprehensible moments of the above program can be read in the following article working with char V C++ for Beginners

Otherwise, the given example of how to read lines from a text file in C++ should be accessible and quite understandable. This is not the optimal implementation option right now, and I missed some important points, but since we are starting to learn the C++ language, this is quite enough for now. Later I will probably get to what I missed, but now I need to perceive only the most necessary.

If you and I understand this material, it means we have taken a small step towards our professionalism.

Note:
break ;– This is the command that exits the loop. We have if the cycle counter for becomes larger than the declared size of the variable char, then we forcefully exit the loop
!= – This is the condition we set. This condition is denoted by inequality
if(a !=b)– Reads as if a not equal b

endl ; – This is to move the cursor to a new line inside the console (as far as I understand)
This command is similar to “\n”

– comparison to identify equality or inequality.

The practical purpose of an enumeration is to define a set of distinct symbolic constants of an integer type.

An example of using enumerated variables:

mo=1, tu, we, th, fr, sa, su ) days;

puts(“ Enter the day of the week (from 1 to 7) : ”); scanf(“%d”, &t_day);

w_day = su; start = mo;

end = w_day -t_day;

printf(“\nMonday is the %d day of the week, \now is the %d day.\n\

Until the end of the week %d days (days). ”, start, t_day, end);

Result of the program: Enter the day of the week (from 1 to 7): 2

Monday is the 1st day of the week, now is the 2nd day. There are 5 days (days) until the end of the week.

18. Files in C language

A file is a set of data located on external media and considered as a single whole during processing. Files contain data intended for long-term storage.

There are two types of files: text and binary. Text files are a sequence of ASCII characters and can be viewed and edited using any text editor.

Binary (binary) files are a sequence of data, the structure of which is determined by software.

The C language has a large set of functions for working with files, most of which are found in the stdio.h and io.h libraries.

18.1. Opening a file

Each file is assigned an internal logical name, which is used later when accessing it. Logical name (file identifier) ​​is

pointer to the file, i.e. to a memory area that contains all the necessary information about the file. The format for declaring a pointer to a file is as follows:

FILE * pointer to file;

FILE – structure type identifier described in the standard library

stdio.h and containing the following information:

type struct(

– the number of unread bytes remaining in the buffer;

the usual buffer size is 512 bytes; as soon as level=0,

the next block of data is read into the buffer from the file;

– file status flag – read, write, append;

– file descriptor, i.e. number defining its no-

unsigned char hold;

– untransmitted character, i.e. ungetc-character;

– size of the internal intermediate buffer;

unsigned char buffer;

– pointer value for access inside the buffer, i.e.

specifies the beginning of the buffer, the beginning of the line, or the current value

The value of the pointer inside the buffer depending on the mode

ma buffering;

unsigned char *curp;

– current value of the pointer for access inside the

fera, i.e. specifies the current position in the exchange buffer

on with the program;

unsigned istemp;

– temporary file flag;

– flag when working with a file;

) FILE;

Before you start working with the file, i.e. To be able to read or write information to a file, it must be opened for access. For this purpose the function is usually used

FILE* fopen(char* file_name, char* mode);

it takes an external representation - the physical name of a file on a medium (floppy disk, hard drive) and matches it with a logical name.

Physical name, i.e. the file name and path to it are specified by the first parameter

– a line, for example, “a:Mas_dat.dat” – a file named Mas_dat.dat located on a floppy disk, “d:\\work\\Sved.txt” – a file named Sved.txt located on the hard drive in the work directory .

Attention! The backslash (\), as a special character, is written twice in a line.

Upon successful opening, the fopen function returns a pointer to the file (hereinafter referred to as the file pointer). On error, NULL is returned. This situation usually occurs when the path to the file to be opened is specified incorrectly. For example, if in the display class of our university you specify a path that is prohibited for writing (usually d:\work\ is allowed).

The second parameter is a line that specifies the file access mode:

w – the file is opened for writing; if there is no file with the given name, it will be created; if such a file exists, then the previous information is destroyed before opening;

r – file opens for read only; if there is no such file, an error occurs;

a – the file is opened to add new information to the end;

r+ – the file is opened for editing data – both writing and reading information is possible;

w+ – the same as for r+;

a+ – the same as for a, only writing can be done anywhere in the file; file reading is also available;

t – the file opens in text mode; b – the file opens in binary mode.

Text mode differs from binary mode in that when a file is opened as a text, the pair of characters “line feed”, “carriage return” is replaced by a single character: “line feed” for all functions for writing data to the file, and for all output functions the character “line feed” " is now replaced by two characters: "line feed", "carriage return".

By default, the file opens in text mode. Example: FILE *f; – a pointer to file f is declared;

f = fopen("d:\\work\\Dat_sp.cpp", "w"); – a file with the logical name f, which has the physical name Dat_sp.cpp, located on drive d, in the work directory, is opened for writing; or more briefly

FILE *f = fopen("d:\\work\\Dat_sp.cpp", "w");

18.2. Closing a file

After working with a file, access to it must be closed. This is done by the int fclose (file pointer) function. For example, from the previous example the file is closed like this: fclose (f);

To close multiple files, a function is introduced, declared as follows: void fcloseall (void);

If you need to change the access mode for a file, you must first close the file and then open it again, but with different access rights. To do this, use the standard function:

FILE* freopen (char*file_name, char *mode, FILE *file_pointer);

This function first closes the file declared file_pointer(as the fopen function does), and then opens the file with file_name and permissions "mode".

The C language has the ability to work with temporary files that are needed only while the program is running. In this case the function is used

FILE* tmpfile (void);

which creates a temporary file on disk with “w+b” access rights; after the program is completed or after the temporary file is closed, it is automatically deleted.

18.3. Write – read information

All actions for reading and writing data to a file can be divided into three groups: character-by-character input-output operations; line-by-line I/O operations; block I/O operations.

Let's look at the main functions used in each of these three groups of operations.

Character-by-character I/O

In character-by-character I/O functions, one character is received from a file or one character is sent to a file:

Row I/O

Line I/O functions transfer from a file or to

Block I/O

Block I/O functions operate on entire blocks

information:

int fread (void*p, intsize,

– reads n blocks of byte size each from the file

int n, FILE *f)

la f to a memory area with pointer p (required

int fwrite (void*p, intsize,

allocate memory in advance for the block to be read);

– writes n blocks of size bytes each from the

int n, FILE *f)

memory area with pointer p to file f.

Formatted I/O is produced by functions.