File operation (file pointer + detailed explanation of sequential read-write function)

Keywords: C C++ stm32

1, Documents

What is a file:

Files on disk are files

1. Classified by file function:

Procedure documents:

Source program file test.c object file test.obj executable program test.exe

Data file:

The content of the file is not necessarily the program, but the data read and written when the program runs, such as the file from which the program needs to read data, or the file that outputs the content, such as data.txt

2. File name

A file should have a unique file ID so that users can identify and reference it.
The file name consists of three parts: file path + file name trunk + file suffix
For example: c:\code\test.txt
For convenience, the file ID is often referred to as the file name.

2, File pointer

Each open file will be followed by a matching file information area to store file information
This information is saved in a structure variable, such as: struct FILE f;. The structure type is declared by the system and named FILE

For example, the stdio.h header file provided by the VS2008 compilation environment contains the following file type declarations:

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

Whenever a FILE is opened, the system will automatically create a variable of FILE structure according to the situation of the FILE and fill in the information in it. Users don't have to care about the details.
Generally, the variables of the FILE structure are maintained through a FILE pointer, which is more convenient to use.

3, Opening and closing of files

1,fopen fclose

ANSIC specifies that fopen function is used to open the file and fclose is used to close the file.

2. "r" - read

#include <stdio.h>

int main()
{
	FILE* pf = fopen("data.txt", "r");
	if (pf == NULL)
	{
		perror("fopen"); 
		// Output:
		// fopen: No such file or directory
		// Because the file does not exist
		return -1;
	}

	// read file

	// Close file
	fclose(pf);
	pf = NULL;

	return 0;
}

Absolute path

#include <stdio.h>

int main()
{
	FILE* pf = fopen("C:\\Users\\Chloe\\Desktop\\data.txt", "r"); // Absolute path
	// FILE* pf = fopen("data.txt", "r"); //  Relative path
	if (pf == NULL)
	{
		perror("fopen");
		return -1;
	}

	// read file

	// Close file
	fclose(pf);
	pf = NULL;

	return 0;
}

3. "w" - write

#include <stdio.h>

int main()
{
	FILE* pf = fopen("C:\\Users\\Chloe\\Desktop\\data.txt", "w"); // A file is generated
	if (pf == NULL)
	{
		perror("fopen");
		return -1;
	}

	// read file

	// Close file
	fclose(pf);
	pf = NULL;

	return 0;
}

4, Sequential reading and writing

1. What functions are there

fputc - the character output function writes a character
fgetc - the character input function reads a character

2. fputc - character output (write)

int fgetc( FILE *stream );

#include <stdio.h>

int main()
{
	FILE* pf = fopen ("C:\\Users\\Chloe\\Desktop\\data.txt", "w");
	if (NULL == pf)
	{
		perror("fopen");
		return -1;
	}

	// Write file
	fputc('b', pf); // Write bit in data.txt
	fputc('i', pf);
	fputc('t', pf);

	// Close file
	fclose(pf);
	pf = NULL;
	 
	return 0;
}

2.1. All output streams

Flow: a highly abstract concept

 C As long as the program of language runs, three streams are opened by default:
 stdout - Standard output stream
 stdin  - Standard input stream
 stderr - Standard error flow
 All types are FILE*

#include <stdio.h>

int main()
{
	fputc('b', stdout);
	fputc('i', stdout);
	fputc('t', stdout);
}

3. fgetc - character input (read)

int fputc( int c, FILE *stream );

3.1. Read from the file

What will be output if you change the file content to abcdef?

#include <stdio.h>

int main()
{
	FILE* pf = fopen ("C:\\Users\\Chloe\\Desktop\\data.txt", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return -1;
	}

	// read file
	int ch = fgetc(pf);                                            
	printf("%c\n", ch); // a
	ch = fgetc(pf);
	printf("%c\n", ch); // b
	ch = fgetc(pf);
	printf("%c\n", ch); // c

	// Close file
	fclose(pf);
	pf = NULL;
	 
	return 0;
}

3.2 read from standard input

It can also be read from standard input, that is, the keyboard

#include <stdio.h>

int main()
{
	int ch = fgetc(stdin);
	printf("%c\n", ch);

	ch = fgetc(stdin);
	printf("%c\n", ch);

	ch = fgetc(stdin);
	printf("%c\n", ch);

}

4. Compare putchar printf getchar scanf

#include <stdio.h>

int main()
{
	fputc('b', stdout);
	// putchar printf("%c", ch);

	int ch = fgetc(stdin);
	// getchar scanf("%c", ch);
	printf("%c\n", ch);
}

5. fputs - text output (write)

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

Put the data into the stream

#include <stdio.h>

int main()
{
	FILE* pf = fopen("data.txt", "w");
	if (NULL == pf)
	{
		perror("fopen");
		return -1;
	}

	// Write file
	// Write a line of data
	fputs("hello world\n", pf);
	fputs("hello bit\n", pf);


	fclose(pf);
	pf = NULL;
}

6. fgets - text entry (read)

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

Read data from stream

Use example:

You want to read 5 characters, but actually read only 4 characters, because there is a \ 0 after it

Change to 20:

7. fprintf - format output

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

Comparison with printf function

Example:

#include <stdio.h>

struct S
{
	int n;
	double d;
};

int main()
{
	struct S s = { 100, 3.14 };

	FILE* pf = fopen("data.txt", "w");
	if (NULL == pf)
	{
		perror("fopen");
		return -1;
	}

	// Write file
	fprintf(pf, "%d %lf", s.n, s.d);

	// Close file
	fclose(pf);
	pf = NULL;

	return 0;
}

8. fscanf - format input

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

Comparison with printf function

Example:

#include <stdio.h>

struct S
{
	int n;
	double d;
};

int main()
{
	struct S s = { 0 };

	FILE* pf = fopen("data.txt", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return -1;
	}

	// read file
	fscanf(pf, "%d %lf", &(s.n), &(s.d));
	
	printf("%d %lf", s.n, s.d);

	// Close file
	fclose(pf);
	pf = NULL;

	return 0;
}

9. fwrite - binary output

Example:

wb "(write only) to output data, open a binary file

#include <stdio.h>

struct S
{
	int n;
	double d;
	char name[10];
};

int main()
{
	struct S s = { 100, 3.24, "zhangsan"};

	FILE* pf = fopen("data.txt", "wb");
	if (NULL == pf)
	{
		perror("fopen");
		return -1;
	}

	// Write in binary
	fwrite(&s, sizeof(s), 1, pf);

	// Close file
	fclose(pf);
	pf = NULL;

	return 0;
}

A bunch of binary files are output in the file

10. fread - binary input

Example:

#include <stdio.h>

struct S
{
	int n;
	double d;
	char name[10];
};

int main()
{
	struct S s = { 100, 3.24, "zhangsan" };

	FILE* pf = fopen("data.txt", "rb");
	if (NULL == pf)
	{
		perror("fopen");
		return -1;
	}

	// Read file - read in binary
	fwrite(&s, sizeof(s), 1, pf);

	// print document
	printf("%d %lf %s\n", s.n, s.d, s.name); // 100 3.240000 zhangsan


	// Close file
	fclose(pf);
	pf = NULL;

	return 0;
}

11. Compare a set of functions

scanf/fscanf/sscanf
printf/fprintf/sprintf

scanf: reads formatted data from the standard input stream (keyboard)
printf: output formatted data to standard output (screen)

fscanf: read formatted data from all input streams
fprintf: output formatted data to all output streams (screen / file)

What do sscanf and sprintf mean?

sscanf and sprintf

Read formatted data from a string
Write formatted data to string

give an example:

#include <stdio.h>

struct S
{
	int n;
	double d;
	char name[10];
};

int main()
{
	char arr[100] = { 0 };
	struct S s = { 100, 3.14, "zhangsan" };

	// Converts a formatted data into a string
	sprintf(arr, "%d %lf %s\n", s.n, s.d, s.name);

	//  Print
	printf("%s\n", arr);

	return 0;
}
Output: 100 3.140000 zhangsan Thus, sprintf is used to: Convert the formatted data into the corresponding string

How to parse the formatted structure from arr and put it into tmp:

#include <stdio.h>

struct S
{
	int n;
	double d;
	char name[10];
};

int main()
{
	char arr[100] = { 0 };
	struct S s = { 100, 3.14, "zhangsan" };

	struct S tmp = { 0 };

	// Converts a formatted data into a string
	sprintf(arr, "%d %lf %s\n", s.n, s.d, s.name);

	// Print as string
	printf("%s\n", arr); // 100 3.140000 zhangsan

	// Extract a formatted data from the string in the arr
	sscanf(arr, "%d %lf %s", &(tmp.n), &(tmp.d), tmp.name);

	// Printed in formatted form
	printf("%d %lf %s\n", tmp.n, tmp.d, tmp.name); // 100 3.140000 zhangsan
	
	return 0;
}
Thus, the function of sscanf is: Read a formatted data from a string (convert a string into a formatted data)

Optimize address book program

File version:

[Contact] structure + dynamic memory management + file storage to realize simple address book code

Posted by dujed on Mon, 27 Sep 2021 02:22:28 -0700