[C Language] Detailed explanation of file operations


(zero) introduction

        The terminal is the interface in the computer system that interacts with the user.

 

        In previous programs, we input data using the keyboard through the terminal and output information through the screen.

        However, if we don't want to enter the data manually, but in the file, input it at one time;

        If we do not want the data to be lost, but store the output data in a file,

        You need to use a new operation - file operation.

0.1What is a file?


        Files are a form of data storage in computer systems;

        Such as text, images, audio, video, etc.


(1) Documents 

1.1 Why use files?


        When the program is running, the data of the program we wrote is stored in the computer's memory; if the program exits, the memory will be reclaimed by the operating system, and the data will be lost; when the program is run again, the data of the last program cannot be obtained.

        If you want to save data persistently, you must use files.

1.2 Features of the file: 

        Files can be created, read, edited, deleted by applications. They are the basic units for storing and transmitting data in computer systems;

        Files can be named and stored on the computer’s storage media;

        Files can also be distinguished between different types of files based on their format and extension. For example, .txt files are plain text files.

1.2.1 File name


        

 

        The file name is the name used to identify and distinguish the file. It is a unique identifier for a file in the file system.

        The purpose of the file name is to facilitate user identification and reference.


The file name contains 3 parts: file path + file name trunk + file suffix
For example: c:\code\test.txt
Key points: When quoting file names in C source files, be sure to use two slashes to escape them into one slash

Escape character: " \\ ==   \   "

1.3 Classification of files 


        But in programming, we generally talk about two types of files: Program files and data files.

1.3.1 Program files

        A program file is a file that contains computer program code.


        For example: ".c" files represent C language program files, ".java" files represent Java program files, ".py" files represent Python program files, etc.

         However, the program file is not the file we want to discuss in depth, because we are writing the code in the program file, and the file required for file operations is not the program file, but the data document.

1.3.2 Data files


        The content of the file is not necessarily program code, but can also be data read and written when the program is running. For example, some files are read by the program when the program is running, and at the same time receive and store the data output by the program - these provide input data and accept output. The data file is the data file.


        The input and output of the data we processed before were all targeted at the terminal, that is, inputting data from the keyboard of the terminal and running the results Displayed from the terminal to the monitor (screen).


        In fact, sometimes we output information to the disk, and when needed, read the data from the disk into the memory for use. What is processed here is the file on the disk, which is the meaning of using the file.


1.3.2.1 Binary files and text files?


        ​​ ​ Depending on how the data is organized, data files are called text files or binary files.


        Data is stored in binary form in the memory. If it is output to external memory without conversion, it is a binary file.

        Normally, we cannot read binary files


        If it is required to be stored in ASCII code on external memory, it needs to be converted before storage. Files stored in the form of ASCII characters are text files.

How to visually understand binary files and text files?

        If we store 10000, ‘a’, etc. in the memory, how are they stored in the memory?

        For characters, due to the existence of the ASCII table, they are the same whether in binary form or text form;

        For numbers, it is different. Take 10000 as an example and see how it is stored in the memory?

example:

        When in ASCII form: each bit requires one byte, 5 bytes are required;

        When in binary form: 10000 is an integer by default, requiring only 4 bytes.

The storage of numbers in memory is still very different.


  At this point, let’s sort out our thoughts——>

summary:

 


(2) Opening and closing files

         In order to better explain file operations, we must first introduce the concept of "stream";

2.1 What is "flow"


        The purpose of our program is to solve problems, that is to say:

        The program needs to obtain information from the outside and output the information after processing. However, different devices have different channels for inputting information. In order to facilitate the program to obtain information from the outside and output information, the C language abstracts the concept of streams.


        C programs perform data input and output operations on files, screens, keyboards, etc. through stream operations.
        Generally speaking, if we want to write data to a stream or read data from a stream, we must open the stream, then operate, and then close the stream.


2.1.1 Standard stream


So why do we input data from the keyboard and output data to the screen without opening the stream?


That's because when the C language program is started, 3 streams are opened by default:


• stdin - standard input stream. In most environments, input is from the keyboard. The scanf function reads data from the standard input stream.


• stdout - the standard output stream. In most environments, it is output to the monitor interface. The printf function outputs information to the standard output stream.

——————The standard input and output stream, to put it bluntly, is the keyboard and screen.


• stderr - the standard error stream, output to the monitor interface in most environments.


        After these three streams are opened by default, we can directly perform input and output operations using functions such as scanf and printf.


        The types of the three streams stdin, stdout, and stderr are: FILE*, usually called a file pointer.


        In C language, various operations of the stream are maintained through the file pointer of FILE*.


2.2 File pointer

        Each used file has a corresponding file information area opened in the memory, which is used to store the relevant information of the file (such as the name of the file, the file status and the current location of the file, etc.). This information is stored in a structure variable. The structure type is declared by the system and named FILE.
        

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

For example, the <stdio.h> header file provided by VS2013 has the above file type declaration:

        The contents of the FILE type 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 the FILE structure based on the file's condition and fill in the information, so the user does not have to care about the details.

        This structure stores the key information of the file. We indirectly operate the file by operating the objects in the structure:


2.3 Opening and closing files


The file should be opened before reading or writing, and the file should be closed after use.


        Use the fopen function to open a file. While opening the file, a FILE* pointer variable pointing to the file will be returned, which is equivalent to establishing a relationship between the pointer and the file.


ANSIC stipulates to use the fopen function to open the file and fclose to close the file.
 

//打开⽂件
FILE * fopen ( const char * filename, const char * mode );
//关闭⽂件
int fclose ( FILE * stream );

There are many ways to open files. Mode indicates the file opening mode. The following are the file opening modes:

How to use the file 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” (add) Add data to the end of the 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” (add) Add data to the end of a binary file Create a new file
"r+" (read and write) For reading and writing, open a text file Error
"w+" (read and write) For reading and writing, a new file is recommended Create a new file
"a+" (read and write) Open a file and read and write at the end of the file Create a new file
"rb+" (read and write) Open a binary file for reading and writing Error
“wb+” (读
訳)
For reading and writing, create a new binary file Create a new file
“ab+”(读
訳)
Open a binary file and read and write at the end of the file Create a new file

        "r" "w" "a" are the three basic opening methods - just write "r" "w" "a" to open a text file, "rb" "wb" "ab" to open a binary file.

         “r+” “w+” “a+” “rb+” “wb+” “ab+” is a compound operation, which is an opening method that can read and write at the same time.


 

2.4 Reading and writing files

        There are two types of file reading and writing: sequential reading and writing and random reading and writing. 

For sequential reading and writing, C language provides standard library functions, which are included in <stdio.h>.

 

Introduction to sequential read and write functions

Function name Function Applicable to
fgetc Character input function All input streams
fputc character output function All output streams
fgets Text line input function All input streams
fputs Text line output function All output streams
fscanf Format input function All input streams
fprintf Format output function All output streams
fread Binary input File
fwrite Binary output File

From these function declarations, we can roughly understand how to use these functions; 

 

 

 

 

 

 

 If you want to learn more, please see Cplusplus.com

(stdio.h) - C++ Reference (cplusplus.com)icon-default.png?t=N7T8https://legacy.cplusplus.com/reference/cstdio/


The way to open a file is the premise, reading and writing are operations, closing files is a habit, and leaving the pointer blank is the gap between you and others.

 

        The above applies to all input streams generally refers to the standard input stream and other input streams (such as file input streams); all output streams generally refers to the standard output stream and other outputs. Stream (such as file output stream)

        To facilitate understanding, here are some application examples:

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

struct re_col
{
	char name[20];
	char us_n[20];
	char us_s[20];
	int age;
};

typedef struct re_col R;

int main()
{
	printf("请输入注册信息>用户名-账号-密码-年龄\n");
	
	FILE* pf = fopen("C:\\Users\\35587\\Desktop\\register collum","w");
	if(pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	
	R* p = (R*)malloc(sizeof(R)*1);
	if(p == NULL)
	{
		perror("malloc");
		return 1;
	}
	
	scanf("%s%s%s%d",p->name,p->us_n,p->us_s,&(p->age));
	
	fprintf(pf,"%s %s %s %d",p->name,p->us_n,p->us_s,p->age);
	
	fclose(pf);
	pf = NULL;
	
	free(p);
	p = NULL;
	
	return 0;
}

         Based on the input, the information is stored in the file register collum;

#include<stdio.h>
int main1()
{
	FILE* pf = fopen("C:\\Users\\35587\\Desktop\\register collum","r");
	if(pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	
	int ch = fgetc(pf);
	
	if(feof(pf))
	{
		puts("EOF had been reached");
	}
	else if(ferror(pf))
	{
		puts("read failure");
	}
	printf("%d",ch);
	
	fclose(pf);
	pf = NULL;
	return 0;
}

int main2()
{
	FILE* pf = fopen("C:\\Users\\35587\\Desktop\\register collum","aw");
	if(pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	
	fputs("iiiii\n",pf);
	fclose(pf);
	pf = NULL;
	
	return 0;
}

int main3()
{
	FILE* pf = fopen("C:\\Users\\35587\\Desktop\\register collum","a");
	if(pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fputs("abni",pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

int main4()
{
	FILE* pf = fopen("C:\\Users\\35587\\Desktop\\register collum","r");
	if(pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	char str[50] = {0};
	fgets(str,6,pf);
	fprintf(stdout,"%s\n",str);
	
	fclose(pf);
	pf = NULL;
	return 0;
}

int main5()
{
	FILE* pf = fopen("C:\\Users\\35587\\Desktop\\register collum","aw");
	if(pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fputs("watink",pf);
	
	fclose(pf);
	pf = NULL;
	
	return 0;
}

int main6()
{
	FILE* pf = fopen("C:\\Users\\35587\\Desktop\\register collum","r");
	if(pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	
	char str1[50];
	
	fscanf(pf,"%s",str1);
	printf("%s\n",str1);//检验是否读取成功
	
	fclose(pf);
	pf = NULL;
	return 0;
}

int main7()
{
	FILE* pf = fopen("C:\\Users\\35587\\Desktop\\register collum","w");
	if(pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fprintf(pf,"abcded\n");
	fclose(pf);
	pf = NULL;
	return 0;
}

int main()
{
	FILE* pf1 = fopen("C:\\Users\\35587\\Desktop\\register collum","r");
	if(pf1 == NULL)
	{
		perror("fopen_1");
		return 1;
	}
	FILE* pf2 = fopen("data_copy.txt","w");
	if(pf2 == NULL)
	{
		fclose(pf1);
		pf1 = NULL;
		perror("fopen_2");
		return 1;
	}
	//op
	char ch;
	while((ch = fgetc(pf1)) != EOF)
	{
		fputc(ch,pf2);
	}
	
	fclose(pf1);
	pf1 = NULL;
	fclose(pf2);
	pf2 = NULL;
	return 0;
}

 



2.5 Random reading and writing of files

        The actual meaning of random reading and writing is that we can control the position of reading and writing, rather than being truly "random".​ 


fseek


Position the  file pointer based on the position and offset of the file pointer.  


ftell


Returns the offset of the file pointer relative to the starting position


rewind


Return the position of the file pointer to the starting position of the file


 Application examples of rewind:


int main()
{
	FILE* pf = fopen("C:\\Users\\35587\\Desktop\\data.txt","a+");
	if(pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	char str[50];
	fgets(str,6,pf);
	printf("%s\n",str);
	int c = ftell(pf);
	printf("%d\n",c);
	rewind(pf);//回到起始位置

	fputs("acccsffe\n",pf);
	int c1 = ftell(pf);
	printf("%d\n",c1);
	
	fclose(pf);
	pf = NULL;
	
	return 0;
}

 

Finished~
 

Guess you like

Origin blog.csdn.net/2301_79465388/article/details/135032679