file operations (1)

content

1. What is a document?

2. So why do we need to use files? 

3. Documents

3.1 Program files

3.2 Data files

3.3 File name

4 Opening and closing of files

4.1 File pointers

4.2 Opening and closing of files

5. Sequential reading and writing of files

  5.1fput function (put characters into a file)

5.2fgetc function (get (get) characters from a file)

 5.3 fputs function (put string into (put) file)

 5.4 fgets function (get (get) string from file)

 5.5fprintf function (put data to file in formatted form)

5.6 fscanf function (get formatted data from file)

5.7 Understanding sprintf and sscanf 

1.sprintf function (write formatted data into a string)

2.sscanf function (read a piece of formatted data from a string)


 

1. What is a document?

file on the hard disk

But in programming, we generally talk about two kinds of files: program files and data files (classified from the perspective of file functions).

2. So why do we need to use files? 

By using files, we can store data directly on the hard disk of the computer, thus achieving data persistence.

3. Documents

3.1 Program files

Including source program files (suffixed with .c ) , object files ( windows environment, suffixed with .obj ) , executable programs ( windows environment, suffixed with .exe ).

3.2 Data files

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 from which the content is output.

Generally, when we process data, we input data through the keyboard, and the result will be displayed on the monitor. But sometimes we may need to output the information to the disk for storage, and then read the data from the disk into the memory for use when we need it. Here, the file on the disk is processed.

It doesn't matter if you don't understand it very well. The following content is all about data files. Let's have an impression first, and continue to look down.

3.3 File name

A file must have a unique file identifier for user identification and reference.
The file name contains 3 parts: file path + file name trunk + file suffix
For example: d:\code\test.txt
For convenience, the file identifier is often referred to as the file name .

4 Opening and closing of files

4.1 File pointers

In the buffered file system, the key concept is " file type pointer " , or " file pointer " for short .
Each used file opens up a corresponding file information area in the memory, which is used to store the relevant information of the file (such as the name of the file, the state of the file and the current location of the file, etc.). This information is stored in a structure variable. The structure type is declared systematically and named FILE .
For example, the stdio.h header file provided by the VS2013 compilation environment has the following file type declaration
struct _iobuf {
        char *_ptr;
        int   _cnt;
        char *_base;
        int   _flag;
        int   _file;
        int   _charbuf;
        int   _bufsiz;
        char *_tmpfname;
       };
typedef struct_iobuf FILE;
The contents of the FILE types of different C compilers are not exactly the same, but they are similar.
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, the user does not need to care about the details.
Generally , the variables of this FILE structure are maintained through a FILE pointer , which is more convenient to use.
Next we can create a pointer variable of FILE* :
FILE* pf;//文件指针变量
Define pf to be a pointer variable to data of type FILE . You can make pf point to the file information area of ​​a file (it is a structure variable). The file can be accessed through the information in the file information area. That is, the file associated with it can be found through the file pointer variable .
E.g:

4.2 Opening and closing of files

  • The file should be opened before reading and writing, and should be closed after the end of use .
  • When writing a program, when opening a file, it will return a FILE* pointer variable to point to the file, which is also equivalent to establishing the relationship between the pointer and the file.
  • ANSIC stipulates that the fopen function is used to open the file and fclose to close the file
//打开文件
FILE *fopen( const char *filename, const char *mode )
//关闭文件
int fclose( FILE *stream )
  •  filename can be added with the file path, but don't forget to escape \ to prevent it from being considered an escape character
  • Stream represents a stream, which is an abstract concept, which is associated with external devices (keyboard, screen, U disk, hard disk, network card...), for example, if we need to write data, write it to the stream, and take data from the stream There are many kinds of streams, including file streams (for reading and writing files)

besides

(As long as a c program runs, these three streams are opened by default)

  1. Standard input stream stdin --> keyboard
  2. Standard output stream stdout -- "screen // are all FILE* types
  3. standard error stream stderr --> screen
  • Absolute path : the path starting from the drive letter, for example: C:\2022code\vs2019\test4_13\1.jpg
  • Relative path : refers to the path of the directory where the current file resource is located, then the relative path above is 1.jpg, and the strict writing method is .\1.jpg
  • When describing relative paths, .\ represents the current path, and ..\ represents the previous path

Open mode (mode) :

How the file is used
meaning
If the specified file does not exist
"r" (read only)
To enter data, open an existing text file
error
"w" (write only)
To output data, open a text file
create a new file
“A” (additional)
Append data to the end of a text file
create a new file
"rb" (read only)
To enter data, open a binary file
error
"wb" (write only)
To output data, open a binary file
create a new file
“Ab” (additional)
Append data to the end of a binary file
error
"r+" (read and write)
Open a text file for reading and writing
error
"w+" (read and write)
For reading and writing, a new file is suggested
create a new file
"a+" (read and write)
Open a file for reading and writing at the end of the file
create a new file
"rb+" (read and write)
Open a binary file for reading and writing
error
"wb+" (read and write)
Create a new binary file for reading and writing
create a new file
"ab+" (read and write)
Open a binary file for reading and writing at the end of the file
create a new file

for example:
 

#include<stdio.h>
int main()
{
	//打开文件
	FILE* pf = fopen("test.txt", "r");//注意看电脑文件扩展名有没有露出来
	//可以打开其他路径的文件
	if (NULL ==pf)
	{
		perror("fopen");
		return;
	}
	//读文件
	//关闭文件
	//fclose(NULL);//fclose不可以传NULL,error
	//写文件
	int ch = 0;
	while ((ch = fgetc(pf) != EOF))//读取的是字符,字符串末尾是\0
	{
		printf("%c ", ch);
	}
	fclose(pf);//和free的用法差不多
	pf = NULL;
	return 0;
}

Note here: 1. fclose() cannot pass a null pointer, and an error will be reported

 2. Before opening the file, check whether the file extension under the path is opened to prevent errors.

5. Sequential reading and writing of files

Features Function name apply to
character input function fgetc  all input streams
character output function fputc  all output streams
Text line input function fgets all input streams
Text line output function fputs all output streams
format input function fscanf all input streams
formatted output function fprintf all output streams
binary input fread document
binary output fwrite document

The objects of the following functions are all files 

  5.1fput function (put characters into a file)

int fputc( int c, FILE *stream ); 

c is a character

Note: When writing, the mode is w 


int main()
{
	FILE* pf = fopen("test.txt", "w");// w 表示只写入数据存到文本文件中
	if (NULL ==pf)
	{
		perror("fopen");
		return;
	}
	//写文件
	char ch = 'a';
	for (ch = 'a';ch <= 'z';ch++)//将字符a~z存到文件中
	{
		fputc(ch, pf);
	}
	//int ch = 0;
	//while ((ch = fgetc(pf) != EOF))//读取的是字符,字符串末尾是\0
	//{
	//	printf("%c ", ch);
	//}
	fclose(pf);
	pf = NULL;
	return 0;
}

After putting the data, we use fgetc to read it 

5.2fgetc function (get (get) characters from a file)

int fgetc( FILE *stream );
  •  Returns the ascaII code value of the read character
  • EOF is returned when end of file or an error is encountered

Note: When reading, the mode is r 

int main()
{
	FILE* pf = fopen("test.txt", "r");// r 表示只读取数据存到文本文件中
	if (NULL ==pf)
	{
		perror("fopen");
		return;
	}
	//写文件
	//char ch = 'a';
	//for (ch = 'a';ch <= 'z';ch++)//将字符a~z存到文件中
	//{
	//	fputc(ch, pf);
	//}
	int ch = 0;
	while ((ch = fgetc(pf) != EOF))//读取的是字符,字符串末尾是\0
	{
		printf("%c ", ch);
	}
	fclose(pf);
	pf = NULL;
	return 0;
}

fputc and fgetc apply to all input and output streams
int main()
{     int ch = fgetc(stdin);//can also be read directly on the keyboard     //printf("%c\n",ch);     fputc(ch, stdout);// The data that can be entered on the keyboard can be put directly into the file     return 0; }  




 5.3 fputs function (put string into (put) file)

int fputs( const char *string, FILE *stream );
int main()
{
	FILE* pf = fopen("test.txt", "w");
	if (NULL ==pf)
	{
		perror("fopen");
		return;
	}
	//以写的形式打开文件会销毁原来的内容,重新输入(覆盖)
	fputs("qwertyuiop\n",pf);//这里可以在字符串后面加上换行操作
	fputs("xxxxxxxxxx\n", pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

 

 5.4 fgets function (get (get) string from file)

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

 string is a string

 n is the maximum number of characters to read

int main()
{
	char arr[256] = { 0 };
	FILE* pf = fopen("test.txt", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return;
	}
	//读一行
	//fgets(arr,256,pf);//这里最多读255个字符,有一个留给‘\0'
	//printf("%s", arr);
	//在不知道文件中有多少字符时
	while (fgets(arr, 256, pf) != NULL)
	{
		printf("%s", arr);
	}
	fclose(pf);//和free的用法差不多
	pf = NULL;
	return 0;
}

 

 5.5fprintf function (put data to file in formatted form)

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

may not be easy to understand

Let's first compare the printf function we have learned

int printf( const char *format [, argument]... );

It is found that only one more pointer to the file needs to be passed in, and the rest of the usage is the same.

struct s
{
	char name[20];
	int age;
	int score;
};
//格式化输出函数fprintf->可以将结构体等一些变量格式化放到文件里
int main()
{
	struct s s = { "李四",18,100 };
	FILE* pf = fopen("test2.txt", "w");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//写文件
	fprintf(pf, "%s %d %d", s.name, s.age, s.score);
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

5.6 fscanf function (get formatted data from file)

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

Let's also compare the scanf function to facilitate understanding

int scanf( const char *format [,argument]... );

//fscanf函数
//格式化输入函数fscanf->可以将文件中结构体等一些信息格式化放到变量中
struct s
{
	char name[20];
	int age;
	int score;
};
int main()
{
	struct s s = { 0 };
	FILE* pf = fopen("test2.txt", "r");//读取打开文件的信息
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//读文件
	fscanf(pf, "%s %d %d", s.name, &(s.age), &(s.score));
	//打印在屏幕上
	//printf("%s %d %d", s.name,s.age, s.score);
	fprintf(stdout,"%s %d %d", s.name, s.age, s.score);
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

5.7 Understanding sprintf and sscanf 

1.sprintf function (write formatted data into a string)

int sprintf( char *buffer, const char *format [, argument] ... );

 buffer is a pointer to store a string, the rest of the usage is the same as the printf function

struct s
{
	char name[20];
	int age;
	int score;
};

int main()
{
	char buf[256] = { 0 };
	struct s s = { "lisi",18,95 };
	sprintf(buf, "%s %d %d", s.name, s.age, s.score);
	printf("%s\n", buf);
	return 0;
}

 

2.sscanf function (read a piece of formatted data from a string)

int sscanf( const char *buffer, const char *format [, argument ] ... );

buffer is a pointer to store a string, the rest of the usage is the same as the scanf function

struct s
{
	char name[20];
	int age;
	int score;
};
int main()
{
	char buff[256] = { 0 };
	struct s s2 = { "lisi",18,95 };
	struct s s1 = { 0 };
	//sprintf(buff, "%s %d %d", s2.name, s2.age, s2.score);
	//printf("%s\n", buff);
	//从buf字符串中提取结构体数据
	sscanf(buff, "%s %d %d", s1.name, &(s1.age), &(s1.score));
	printf("%s %d %d", s1.name, s1.age, s1.score);
	return 0;
}

 

scanf / printf       

is a formatted input/output statement for stdin/stdout.

fscanf / fprintf   

is a formatted I/O statement for all input streams/all output streams, including the functionality of the above functions .

sscanf / sprintf   

sscanf reads formatted data from a string, and sprintf outputs (stores) the formatted data into a string .

It is a pity that the above content cannot operate on pictures. If you want to make a small game with pictures by yourself, you can learn the easyx graphics library . The blogger is a freshman and only recently learned about it.

That's all for today, thanks for watching 

Guess you like

Origin blog.csdn.net/weixin_63451038/article/details/124056829