125-C language to realize file operation

A file refers to a collection of data stored on external media.

In order to simplify the operation of various devices, so that users do not have to distinguish between various devices, the operating system treats all devices as files. From the perspective of the operating system, every input and output device is a file. The keyboard is the standard input device and its file identifier is "stdin", and the screen is the standard output device, and its file identifier is "stdout"

Data flows from one place to another like a pipeline, so the input and output data is often called data flow

The data flowing from the file (external memory) to the memory is called the input stream, and the data flowing from the memory to the file (external memory) is called the output stream
Insert picture description here
file name. The
file must have a unique file identifier for the user to identify and use.
File identification includes three parts: file path + file name trunk + file suffix name. As shown below:
Insert picture description here
The function of the file suffix is the default application for the associated operating system to open this type of file . The mp3 file above is associated with QQ Music by default. Of course this can be modified

Classification of files
According to the organization of data, files can be divided into binary files and text files.
Binary file : The data is stored in the memory in binary form. If it is saved directly to the file without conversion, it is a binary file.
Common binary files include picture files, audio files, video files, executable program files, etc. These files cannot be viewed directly with Notepad, and must be parsed by specific applications. For example, mp3 audio files must be played through an mp3 player

Insert picture description hereText file : also called ASCII file, which stores the code of each character. Common files such as ".txt"
Insert picture description here

How is a piece of data stored in a file? For example, the number 123456.
If it is stored in a text file, the codes of character 1, character 2, character 3, character 4, character 5, and character 6 are 6 bytes in total.
If in a binary file, the number 123456 is an integer and occupies 4 bytes. The storage is as follows:
Insert picture description here
Binary files do not need to be converted, which saves time when reading and writing, and saves space compared to text files, so binary files are the most widely used

File operations

The file pointer is also called the file type pointer, which is used to save the information of each opened file. The file pointers of all files opened in the system at the same time are unique, and the file pointer can be regarded as the unique identification of file operations. Use "FILE *" in C code to represent
FILE *fopen(const char filename,const char mode);

fopen function: create or open a file. The parameter
filename : the name of the file that needs to be created or opened;
mode the way to open the file. Commonly read "r", write "w", binary read "rb", binary
write "wb", etc. For other methods, please refer to the help manual

Note that if the file opened by "w" and "wb" already exists, clear the data of the original file and open
it again. If the file does not exist, create a new file and open it. "R" and "rb" when opening the file, the file must exist, otherwise the opening fails.
Return value: If the file is opened successfully, the file can be operated through the file pointer. Remember to close the file at the end of the file operation, otherwise the file pointer of the memory leak will appear, and it will be NULL if it fails.

int fclose(FILE *stream);

fclose function: used to close open files. Parameter
stream: file pointer to be closed

int main()
{
    
    
	FILE *fw = fopen("D:\\1.txt","w");
	assert(fw != NULL);//断言文件打开成功
	//文件操作过程省略......
	fclose(fw); //关闭文件
	return 0;
}

Sequential reading and writing of files The
read and write operations are mainly done through two functions fread and fwrite. The function prototype is as follows:
size_t fread(void *buffer,size_t size,size_t count,FILE *stream);

fread function: used to read data from the file, the parameters are:
buffer: store the data read from the file;
size: the number of bytes of each unit data;
count: how many unit data are read in total;
stream: File pointer to read data.
Return value: The number of unit data successfully read is very important. If this value is less than count, it can be judged that the file has been read completely

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

The fwrite function: used to write data to the file, where the parameters are: buffer: the data written in the file;
size: the number of bytes of each unit data;
count: how many unit data are
written in total; stream: the file written pointer.
Return value: the number of unit data successfully written

Read and write text files

//往文件写入文本数据
int main()
{
    
    
	FILE *fw = fopen("1.txt","w"); //创建或打开一个新文件
	assert(fw != NULL);
	char *str = "林泽宇林泽宇"; //写入文件的数据
	fwrite(str,sizeof(char),strlen(str),fw);//写数据
	fclose(fw); //关闭文件
	return 0;
}
//从文件读取文本数据
int main()
{
    
    
	FILE *fr = fopen("1.txt","r"); //打开已经存在的文件
	assert(fr != NULL); //如果文件不存在则打开失败
	char str[100] = ""; //存放读取的数据
	int len = fread(str,sizeof(char),100,fr);//从文件读取数据
	fclose(fr); //关闭文件
	printf("len=%d,%s\n",len,str);
	return 0;
}

Reading and writing binary files
Reading and writing binary files is similar to text files, except that the second parameter of fopen is slightly different.

//往文件写入二进制数据
int main()
{
    
    
	FILE *fw = fopen("2.txt","wb"); //b 表示二进制文件
	assert(fw != NULL);
	int arr[] = {
    
    1,2,3,4,5,6,7,8,9,10};//写入的数据
	fwrite(arr,sizeof(int),10,fw); //整个整型数组直接写入文件
	fclose(fw);
	return 0;
}

Due to the written binary data, this file cannot be viewed directly.
Insert picture description here
Binary files need to be parsed by programs and cannot be viewed directly, as shown in the following code:

//从文件读取二进制数据
int main()
{
    
    
	FILE *fr = fopen("2.txt","rb");//b 表示二进制文件
	assert(fr != NULL);
	int buf[100]; //保存读取的数据
	int len = fread(buf,sizeof(int),100,fr);
	fclose(fr);
	printf("len=%d\n",len);
	for(int i=0;i<len;i++) //输出读取的数据
		printf("%d ",buf[i]);
	return 0;
}

Random read and write files
Random read and write are not read and write sequentially according to the physical location of the data in the file, but can access data at any location.
Listening to a song from the beginning is sequential reading, if you directly drag the progress bar to the first minute, it is random reading. When watching a movie, skipping the title is also random.
To achieve random read and write operations, the most important thing is the file position mark (also called the file position pointer). This mark is similar to a cursor and marks the starting position of the next reading and writing.

Insert picture description here
The key function of random reading and writing is the fseek function of moving file position identification.
int fseek(FILE *stream,long offset,int origin);

fseek function: move the file location identification, the parameters are as follows: stream: the file that needs to move the file location identification;
offset: the number of bytes of the offset, the positive number moves backward, the negative number moves forward;
origin: the reference point, supports three references point. SEEK_SET file header, SEEK_CUR file location identifies the current position, SEEK_END file end

Here are a few examples of adjusting the file position mark. Move to the tenth byte of the beginning of the file: fseek (fp,10, SEEK_SET); Move
to the last 50 bytes of the current position: fseek (fp,50, SEEK_CUR); Move
to the 10th last word of the file Section: fseek (fp,-10, SEEK_END);

Example: Find the size of a file, that is, the number of bytes occupied

#include<stdio.h>
//求 1.cpp 文件占用的字节数
int main()
{
    
    
	FILE *fr = fopen(1.cpp","rb");//打开文件
		fseek(fr,0,SEEK_END); //将文件位置标识移到文件结尾
	long sz = ftell(fr); //测定当前文件位置标识的位置
	printf("该文件共%ld 个字节\n",sz);
	fclose(fr);
	return 0;
}

The ftell function is used to determine the current position of the file position marker, and the return value is the number of bytes from the current position to the beginning of the file

Example: Repeat reading the first 10 characters of the file 5 times

int main()
{
    
    
	char buf[100] = "";
	FILE *fr = fopen("1.txt","r");
	assert(fr != NULL);
	for(int i=0;i<5;i++) //读取 5 遍
	{
    
    
		fread(buf,sizeof(char),10,fr);//读取 10 个字符
		printf("%s\n",buf);
		memset(buf,0,100); //清空 buf
		fseek(fr,0,SEEK_SET); //文件位置标记跳到文件开头
	}
	fclose(fr);
	return 0;
}

Guess you like

Origin blog.csdn.net/LINZEYU666/article/details/111997119