Reading and writing of files in C language (1)

The previous three parts have been introduced to you, and the URL is sent to you for your review. The opening
method is as follows:
File Usage Meaning If the specified file does not exist
"r" (read-only) Error opening an existing text file for input data
" w" (write only) for output data, open a text file create a new file
"a" (append) append data to the end of the text file create a new file
"rb" (read only) for input data, open a binary file error
"wb" (write only) for output data, open a binary file create a new file
"ab" (append) append data to the end of a binary file create a new file
"r+" (read and write) for read and Write, open a text file error
"w+" (read and write) For reading and writing, suggest a new file to create a new file
"a+" (read and write) open a file, read and write at the end of the file to create a new File
"rb+" (read-write) Error opening a binary file for reading and writing
"wb+" (read-write) Create a new binary file for reading and writing Create a new file
"ab+" (read-write) Open a binary File, read and write at the end of the file to create a new file

instance code:

/* fopen fclose example */
#include <stdio.h>
int main ()
{
    
    
  FILE * pFile;
  //打开文件
  pFile = fopen ("myfile.txt","w");
  //文件操作
  if (pFile!=NULL)
 {
    
    
    fputs ("fopen example",pFile);
    //关闭文件
    fclose (pFile);
 }
  return 0;
}

4. Sequential reading and writing of files

4.1 Introduction to sequential read and write functions

Function function names 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
formatted input function fscanf all input streams
formatted output function fprintf all output stream
binary input fread file
binary output fwrite file

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main()
{
    
    
	FILE* pf = fopen("test.txt", "w");//定义一个变量pf,pf指向这个文件信息区,文件信息区和文件本身相关联,这时候我们就可以读或者写或者对文件做一些其他的事情等等
	if (pf == NULL)
	{
    
    
		printf("%s\n", strerror(errno));
		return 1;
	}
	//写文件
	//......
	//关闭文件
	fclose(pf);
	pf = NULL;//设置成空指针使其再也找不到这块空间
	return 0;
}

Some students here may ask, why close the file pointed to by pf?
This is because the file is also a resource. Finally, if you close the file, you will release the resource. The number of files that can be opened by a program is limited. It does not mean that it can be opened indefinitely. There are many files, and if you don’t close this file, it may cause data loss, etc., so be sure to close the file and set it to NULL. Let’s look at the code of
the fputc function .
insert image description here

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main()
{
    
    
	FILE* pf = fopen("test.txt", "w");
	if (pf == NULL)
	{
    
    
		printf("%s\n", strerror(errno));
		return 1;
	}
	char i = 0;
	for (i = 'a'; i <= 'z'; i++)
	{
    
    
		fputc(i, pf);
	}
	//写文件
	//......
	//关闭文件
	fclose(pf);
	pf = NULL;//设置成空指针使其再也找不到这块空间
	return 0;
}

You can copy a copy of the code and test it yourself.
At this time, we will open the test.txt file to see if all the 26 letters we just wrote have been written into the file. Let’s see,
insert image description here
the result belongs to the realization.
Now we want to write it in the form of characters. Take out all the characters in my file, this time we need to use the fgetc function

fgetc function
insert image description here
insert image description here
In short, if a wrong character is read, it will return EOF
Now let's look at the code

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main()
{
    
    
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
    
    
		printf("%s\n", strerror(errno));
		return 1;
	}
	int ch = 0;
	while ((ch = fgetc(pf)) != EOF)
	{
    
    
		printf("%c ", ch);
	}
	//char i = 0;
	//for (i = 'a'; i <= 'z'; i++)
	//{
    
    
	//	fputc(i, pf);
	//}
	//写文件
	//......
	//关闭文件
	fclose(pf);
	pf = NULL;//设置成空指针使其再也找不到这块空间
	return 0;
}

insert image description here
You can see that fgetc reads all the characters in the file.
Now we write a line of data. At this time, we need to use the fputs function. The
fputs function
insert image description here
const char * str, FILE * stream
Write string to stream here means to write the characters Write the string to the stream (that is, the file) for

insert image description here
everyone to see. You may have doubts. Didn’t we write 26 English letters just now? Why are the 26 letters here missing? This is because when you write data to the file again, it will automatically clear all the things you wrote in the original file and then rewrite it. I hope everyone can understand

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main()
{
    
    
	FILE* pf = fopen("test.txt", "w");//"w"改成"a"的时候是追加的意思。我们来看下面的图片
	if (pf == NULL)
	{
    
    
		printf("%s\n", strerror(errno));
		return 1;
	}
	fputs("hello bit", pf);
	//int ch = 0;
	//while ((ch = fgetc(pf)) != EOF)
	//{
    
    
	//	printf("%c ", ch);
	//}
	//char i = 0;
	//for (i = 'a'; i <= 'z'; i++)
	//{
    
    
	//	fputc(i, pf);
	//}
	//写文件
	//......
	//关闭文件
	fclose(pf);
	pf = NULL;//设置成空指针使其再也找不到这块空间
	return 0;
}

FILE pf = fopen("test.txt", "w");//When "w" is changed to "a", it means append. Let's look at the picture below *
insert image description here
Now what should we do if we want to randomly read a line of data, so we introduce the fgets function The string read by
the fgets function
insert image description here
insert image description here
will be copied to the space pointed to by str
The number of characters with the most characters will be Copy it into str,

insert image description here
you can try to understand it yourself

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main()
{
    
    
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
    
    
		printf("%s\n", strerror(errno));
		return 1;
	}
	char arr[20];
	fgets(arr, 5, pf);
	printf("%s\n", arr);//放5的时候最多能够读到4个
	fclose(pf);
	pf = NULL;//设置成空指针使其再也找不到这块空间
	return 0;
}

insert image description here
insert image description here
Here I will introduce the perror function to you, it is more convenient to use some
perror functions

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main()
{
    
    
	FILE* pf = fopen("test", "r");
	if (pf == NULL)
	{
    
    
		//printf("%s\n", strerror(errno));
		perror("fopen");
		return 1;
	}
	char arr[20];
	fgets(arr, 5, pf);
	printf("%s\n", arr);//放5的时候最多能够读到4个
	fclose(pf);
	pf = NULL;//设置成空指针使其再也找不到这块空间
	return 0;
}

/ Here I will introduce the fprintf function to you.
The fprintf function
insert image description here
insert image description here
will give you the code

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//#include<stdlib.h>
#include<errno.h>
#include<string.h>
struct S
{
    
    
	char arr[20];
	int age;
	float score;
};
int main()
{
    
    
	struct S s = {
    
     "zhangsan",25,50.5f };
	FILE* pf = fopen("test.txt", "w");
	if (pf == NULL)
	{
    
    
		//printf("%s\n", strerror(errno));
		perror("fopen");
		return 1;
	}
	fprintf(pf, "%s %d %f", s.arr, s.age, s.score);//fprintf将数据写到文件里面去
	fclose(pf);
	pf = NULL;//设置成空指针使其再也找不到这块空间
	return 0;
}

If you want to read the data from the file, you must introduce the fscanf function
fscanf function
insert image description here
insert image description here

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//#include<stdlib.h>
#include<errno.h>
#include<string.h>
struct S
{
    
    
	char arr[20];
	int age;
	float score;
};
int main()
{
    
    
	struct S s = {
    
     "zhangsan",25,50.5f };
	FILE* pf = fopen("test.txt", "w");
	if (pf == NULL)
	{
    
    
		//printf("%s\n", strerror(errno));
		perror("fopen");
		return 1;
	}
	fscanf(pf, "%s %d %f", s.arr, (&s.age), &(s.score));//fscanf从文件里面去读,将信息从pf指向的文件读出来放到s里面去,再将其打印出来
	printf("%s %d %f", s.arr, s.age, s.score);
	fclose(pf);
	pf = NULL;//设置成空指针使其再也找不到这块空间
	return 0;
}

Introduction to fwrite function
fwrite function
insert image description here
insert image description here
At this time, you find that you have some things that you can’t understand. This is because it is written in binary form
. Time to introduce the fread function
fread function
insert image description here
We write it in binary form, we can read it out in binary form
insert image description here

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//#include<stdlib.h>
#include<errno.h>
#include<string.h>
struct S
{
    
    
	char arr[20];
	int age;
	float score;
};
int main()
{
    
    
	struct S s = {
    
     "zhangsan",25,50.5f };
	FILE* pf = fopen("test.txt", "wb");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return 1;
	}
	//fwrite(&s, sizeof(struct S), 1, pf);
	fread(&s, sizeof(struct S), 1, pf);
	printf("%s %d %f\n", s.arr, s.age, s.score);
	fclose(pf);
	pf = NULL;//设置成空指针使其再也找不到这块空间
	return 0;
}

The end of this chapter!

Guess you like

Origin blog.csdn.net/fjj2397194209/article/details/131313358