Are you still worried about the loss of input data after the program runs? The long article introduces various functions of file operation and various data operations

File operation

πŸ’›πŸ’› Take your own notes ~: Document operation notesπŸ’›πŸ’›
❀️ Welcome friends who like learning C/C + + to work together!! ❀️

introduction

I published an article about the address book a few days ago. After entering my contact information, if I quit the program, my contact information will disappear. The address book we want may not be like this. What we want is that the address book can keep our contact information all the time

Address book article directions: Simple address book implementation, gitee also updated the dynamic memory version of the address book

This article will introduce how to save our contact information through file operation

1, Common file types

The classification of documents is shown in the figure below

1. Procedure documents

  • 🌟 Source program file (suffix. c)

  • 🌟 Target file (windows environment suffix is. obj)

  • 🌟 Executable program (windows environment suffix is. exe)

2. Data files

✨ Sometimes we need to read the data and output the content when running the program

3. File name

✨ I believe everyone is familiar with how the file name is formed

File path + file name trunk + file suffix

  • For example: c:\code\test.txt

2, File pointer

❗ ️ ❗ οΉ₯ operation steps:

  • ⭐ Open file
  • ⭐ Read / write data
  • ⭐ Close file

🌟 Every time we open a file, a pointer will point to a file information area, which is used to store the relevant information of the file (such as file name, file status, current location of the file, etc.)

🌟 This information is stored in a structure variable. The structure type is declared by the system and is called FILE

In fact, in vs2019, corecrt_ This is described in the wstdio. H header file

vs2019 may be deeply encapsulated, which is not easy to observe

Let's take a look at vs2013, which is described in the stdio.h header file

struct _iobuf {
        char *_ptr;
        int   _cnt;
        char *_base;
        int   _flag;
        int   _file;
        int   _charbuf;
        int   _bufsiz;
        char *_tmpfname;
       };
typedef struct _iobuf FILE;

In this way, we can see clearly what data is stored in it

✨ Whenever a FILE is opened, the system will automatically create a variable of FILE structure and fill in the information according to the situation of the FILE

✨ Generally, the variables of the FILE structure are maintained through a FILE pointer, which is more convenient to use

✨ Definition f is a pointer variable pointing to data of type FILE. You can make pf point to the FILE information area (a structure variable) of a FILE. The FILE pointer variable can find the FILE associated with it through the FILE information area.

3, Opening and closing of files

1. Open fopen file

//Open file
FILE * fopen (const char * filename, const char * mode);

❗ ️ ❗ If the opening fails, a null pointer is returned ❗ ️ ❗ ️

  • filename is the file name
  • Mode is the open mode

✨✨ What are the types of mode opening methods

File usagemeaningIf the specified file does not exist
"r" (read only)To enter data, open an existing text fileerror
"w" (write only)To output data, open a text fileCreate a new file
"a" (added)Add data to the end of a text fileCreate a new file
"rb" (read only)To enter data, open a binary fileerror
"wb" (write only)To output data, open a binary fileCreate a new file
"ab" (additional)Add data to the end of a binary fileerror
"r +" (read / write)To read and write, open a text fileerror
"w +" (read / write)A new file is recommended for reading and writingCreate a new file
"a +" (read / write)Open a file and read and write at the end of the fileCreate a new file
"rb +" (read / write)Open a binary file for reading and writingerror
"wb +" (read / write)Create a new binary file for reading and writingCreate a new file
"ab +" (read / write)Open a binary file and read and write at the end of the fileCreate a new file

This paper mainly introduces and understands the first three ways

2. "r" reads the file

Let's try reading the file first

I'll create a new txt file on the desktop first

Write according to the code of the open file, and pay attention to prevent null pointers

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE * f = fopen("file.txt", "r");
    if (f == NULL)
    {
        perror("fopen");//Judge whether the opening is successful
        return -1;
    }

    return 0;
}

❗ ️ ❗ The result is that it tells me that there is no such file!

❗ ️ ❗ ️ ❗ Note: this method of writing only the name is called passing the relative path address. If only the file name is written, the file must be in the same path of the source file to be read successfully

🌟 We need to write all its paths, which is called passing absolute path address

Right click the file, find the properties, and find its path

🌟 Modify the code: note that the combination of \ and letters will cause escape characters, so you need to add \ in front to avoid escape

int main()
{
    FILE * f = fopen("C:\\Users\\yujing wang\\Desktop\\file.txt", "r");
    if (f == NULL)
    {
        perror("fopen");
        return -1;
    }


    return 0;
}

πŸ’’πŸ’’πŸ’’ After running, I still failed to read??

It took me a long time to find out why

πŸ”₯πŸ”₯πŸ”₯ It turns out that when my computer creates a new file, it doesn't need to define what type of file it is. It will be added automatically, and the file.txt I wrote is the file name and TXT is the file type, so I'll check whether the name is correct when looking for its path

This time we will not modify the code, but directly modify the file name

πŸ”₯ This read succeeded!

Let's enter the characters file in the file and try how to print the read characters

fgetc read character function

Parameters and return values

int fgetc( FILE *stream );
int main()
{
    FILE * f = fopen("C:\\Users\\yujing wang\\Desktop\\file.txt", "r");
    if (f == NULL)
    {
        perror("fopen");
        return -1;
    }
    int ret = fgetc(f);
    printf("%c", ret);
    
    ret = fgetc(f);
    printf("%c", ret);
    
    return 0;
}

The operation results are as we wish

3. fclose close file

//Close file
int fclose ( FILE * stream );//The address of the file information area is transmitted

Directly use the above code to open the file and add the close file later

✨✨✨ Note that the pointer does not change after use. You need to change it into a null pointer ✨✨✨

int main()
{
    FILE * f = fopen("C:\\Users\\yujing wang\\Desktop\\file.txt", "r");
    if (f == NULL)
    {
        perror("fopen");
        return -1;
    }

    fclose(f);
    f = NULL;

    return 0;
}

4. "w" write file

πŸ’— We delete the file created on the desktop just now, and then execute the original code, but the opening method is "w"

int main()
{
    FILE * f = fopen("C:\\Users\\yujing wang\\Desktop\\file.txt", "w");
    if (f == NULL)
    {
        perror("fopen");
        return -1;
    }

    fclose(f);
    f = NULL;

    return 0;
}

The result is

✨ There are many newly added files on the desktop. If you write something in the file and run the code, the file will become an empty file again. It's amazing

We can also add characters to the file in the code

fputc character input function

Parameters and return values

int fputc( int c, FILE *stream );

Pass in the file address and write characters to the file

int main()
{
    FILE * f = fopen("C:\\Users\\yujing wang\\Desktop\\file.txt", "w");
    if (f == NULL)
    {
        perror("fopen");
        return -1;
    }
    fputc('f', f);//Character input function
    fputc('i', f);
    fputc('l', f);
    fputc('e', f);

    fclose(f);
    f = NULL;

    return 0;
}

After running, we open the file

We write a file to the file in code

4, Sequential reading and writing of files

Sequential read-write function table

functionFunction nameApply to
Character input functionfgetcAll input streams
Character output functionfputcAll output streams
Text line input function (read contains' \ 0 ')fgetsAll input streams
Text line output functionfputsAll output streams
Format input function (read in one format)fscanfAll input streams
Format output functionfprintfAll output streams
Binary inputfreadfile
Binary output (write as binary)fwritefile

✨ External devices: file, screen, network, CD, floppy disk

✨ A stream is a device that can be read and written to

c language programs open three streams by default when running

Standard output stream - stdout (screen printing, where the screen is the compiler debugging console)

πŸ’« Standard input stream - stdin (keyboard)

πŸ’« Standard error stream - stderr

πŸ’« These stream types are FILE*

The character input function fgetc and character output function fputc have been introduced earlier

1. fputs text line output function

Parameters and return values

int fputs( const char *string, FILE *stream );

Pass parameter, write the text line and the address of the file

0 is returned for success and NULL is returned for failure

First of all, there is no such file on the desktop. We need to write a file with a string content of file

#include <stdio.h>
#include <stdlib.h>

int main()
{
	FILE* p = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "w");
	if (p == NULL)
	{
		perror("fopen");
		return -1;
	}
	fputs("file", p);

	fclose(p);
	p = NULL;

	return 0;
}

The operation structure is that there are more files on the desktop, test.txt, with the content of file, which is much simpler than the previous one character input

After the code runs, let's read the string

2. fgets text line output function

Parameters and return values

char *fgets( char *string, int n, FILE *stream );

Parameter transfer: the location where the string is stored, the number of bytes transferred (no more than the maximum number of bytes), and the file address

ps: the bytes passed here contain '\ 0' by default

The starting address of string is returned successfully, and NULL is returned in case of failure

Go directly to the code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
	FILE* p = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "r");
	if (p == NULL)
	{
		perror("fopen");
		return -1;
	}
	char arr[5] = { 0 };
	char* ret = fgets(arr, 5, p);

	printf("%s\n", arr);
	printf("%s\n", ret);

	fclose(p);
	p = NULL;

	return 0;
}

Operation results:

Both printing methods are available

3. fprintf format output function

Parameters and return values

int fprintf( FILE *stream, 
            const char *format [, argument ]...);

Transmission parameters: file address, formatted memory (this format has a certain format for the content)

Functions in "" similar to printf

Return value: several bytes are successfully written

The code is similar to the previous ones

struct stu
{
	int a;
	char b[4];
}st = {233, "abc"};

int main()
{
	FILE* p = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "w");
	if (p == NULL)
	{
		perror("fopen");
		return -1;
	}
	int ret = fprintf(p, "%d %s", st.a, st.b);

	printf("%d", ret);
	fclose(p);
	p = NULL;

	return 0;
}

effect:

4. fscanf format input function

Parameters and return values

int fscanf( FILE *stream, const char *format [, argument ]... );

Transmission parameters: file address, formatted memory (this format has a certain format for the content)

According to the code that has been output above, let's input it into the structure

#include <stdio.h>
#include <stdlib.h>

struct stu
{
	int a;
	char b[4];
}st;

int main()
{
	FILE* p = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "r");
	if (p == NULL)
	{
		perror("fopen");
		return -1;
	}

	fscanf(p, "%d %s", &(st.a), st.b);
	printf("%d %s\n", st.a, st.b);

	fclose(p);
	p = NULL;

	return 0;
}

Operation results:

5. fwrite binary output function

Parameters and return values

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

Parameters: pointer to the data to be written, byte size of an element, maximum number of elements, and file address

Return value: the number of elements actually written by the book

Experiment:

struct stu
{
	int a;
	char b[4];
}st = {233, "abc"};


int main()
{
	FILE* p = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "wb");
	if (p == NULL)
	{
		perror("fopen");
		return -1;
	}

	int ret = fwrite(&st, sizeof(st), 1, p);

	printf("%d", ret);
	fclose(p);
	p = NULL;

	return 0;
}

Operation results:

Here, letters written in binary form are letters, while binary written numbers we can't see

6. fread binary input function

Parameters and return values

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

Parameters: the pointer points to the position where the read data is placed, the byte size of an element, the maximum number of elements, and the file address

Also read according to the above code

struct stu
{
	int a;
	char b[4];
}st;



int main()
{
	FILE* p = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "rb");
	if (p == NULL)
	{
		perror("fopen");
		return -1;
	}
	fread(&st, sizeof(st), 1, p);

	printf("%d %s", st.a, st.b);
	
	fclose(p);
	p = NULL;

	return 0;
}

It seems that the reading succeeded

Summary

I've been wondering for a long time, 🌟 What is the difference between fprintf and printf? Is there any connection

scanf/fscanf/sscanf

printf/fprintf/sprintf

What are these two groups of very similar functions

functioneffect
scanfRead formatted data from standard input stream (keyboard)
fscanfRead formatted data from all input streams
sscanfRead a formatted data from a string (convert a string into a formatted data)
printfOutput formatted data to standard output (screen)
fprintfOutput formatted data to all output streams (screens / files)
sprintfConvert the formatted data into the corresponding string!

Although we don't use programs to write a txt file, we need to know the operation principle,

🌟 When necessary, it will also bring convenience!

I have Baidu search

In fact, its examples are hidden in our lives πŸ˜†πŸ˜†πŸ˜†~~

Tags: C C++ Windows

Posted on Fri, 08 Oct 2021 05:37:44 -0400 by ricmetal