C language basics (9) file-related operations


A first look at C language in series collection

10. Documents

10.1 Overview of C files

File: A collection of data stored on external media, which is the unit of operating system data management.
The purpose of using data files:
1) Separation of program and data: the change of data file does not cause the change of program
2) Data sharing: different programs can access the data in the same data file
3) It can save the intermediate data or result data of program operation for a long time

File classification:
(1) According to the logical structure of the file
Record file: composed of records with a certain structure (fixed length or variable length)
Stream file: composed of character (byte) data sequence
(2) According to the
common storage medium File: Storage medium file (disk, tape, etc.)
Device file: Non-storage medium (keyboard, monitor, printer, etc.)
(3) According to the organization of
data Text file: ASCII file, each byte stores the ASCII code of one character.
Features of text files: large storage capacity, slow speed, easy to operate on characters
Binary files: data is stored as it is in the storage form in memory
Features of binary files: small storage capacity, fast speed, easy to store intermediate results

File processing method:
buffered file system: high-level file system, the system automatically opens up a memory buffer for the file in use
Non-buffered file system: low-level file system, the user sets the buffer for each file in the program

10.2 File type pointer

File structure FILE:
The buffer file system opens up a file information area in the memory for each file being used, and the file information is described by a system-defined structure named FILE

FILE is defined in studio.h

typedef struct{
    
    
	int _fd;  //	文件号
	int _cleft;  //缓冲区剩下的字符数
	int _mode;  //文件操作方式
	char *_next;  //文件当前读写位置
	char *_buff;  //文件缓冲区位置
}FILE;

File type pointer:
pointer variable description: FILE *fp;
usage: when the file is opened, the system automatically builds the file structure and returns the pointer to it, and the program obtains file information through this pointer to access the file; after the file is closed, it The file structure is freed.
insert image description here

10.3 Opening and Closing Files

10.3.1 Opening of files

C file operations are implemented by calling library functions, including in the studio.h
file. How to use: open the file -- read and write the file -- close the file.
The system automatically opens and closes three standard files:
standard input: keyboard stdin
standard output: monitor stdout
Standard error output: monitor stderr

Open file fopen:
function prototype:

FILE   *fopen (char *name, char *mode)

Function: Open the file according to the specified method
Return value: Open normally, which is a pointer to the file structure; fail to open, return NULL
For example: file opening and testing

FILE *fp;
fp = fopen("a.c""w");
if(fp == NULL){
    
    
	prentf("file open error\n");
	exit(0);
}

How to open the file:

Three basic modes:
"r" (read) mode always opens an existing file, and errors if the file does not exist.
"w" (write) mode creates a new file, if the file already exists, delete the existing file first, and then create a new file.
"a" (append) opens an existing file and appends data to the end of the file.

Three appenders:
"b" (binary) means a binary file.
"t" (or default) means a text file.
"+" means to expand the mode to be readable and writable.

How to open the file meaning
'r' (read-only) open a text file for input
'w' (write only) open a text file for output
'a' (append) Append data to the end of a text file
'rb' (read-only) open a binary file for input
'wb' (write only) open a binary file for output
'ab' (append) Append data to the end of the binary file
'r+' (read and write) Open a text file for reading/writing
' w+ ' (read and write) create a new text file for read/write
' a+ ' (read and write) Open a text file for reading/writing
'rb+' (read and write) Open a binary file for reading/writing
' wb+ ' (read and write) Create a new binary file for read/write
'ab+' (read and write) Open a binary file for reading/writing

10.3.2 Closing of files

Function: Make the file pointer variable "detach" from the file, release the file structure and file pointer
Function prototype: int fclose(FILE *fp);
*fp: the file type pointer returned when the file is opened
Function: close the file pointed to by fp
return value : Normal shutdown is 0, error is non-zero
insert image description here

10.4 Reading and writing files

10.4.1 fputc function and fgetc function

Character I/O: fputc and fgetc
1) fputc
function prototype:

int fputc(int c,FILE *fp)

Function: write one-byte code c into the file pointed to by fp
Return value: success, return c; error, return EOF
2) fgetc
function prototype: int fgetc(FILE *fp)
function: read from the file pointed to by fp One-byte code
Return value: normal, return the read code value; read until the end of the file or an error

End I/O Document I/O
#define putc ( ch, fp ) fputc ( ch,fp )
#define getc ( fp ) fgetc ( fp )
#define putchar ( c ) fputc ( c,stdout )
#define getchar ( ) fgetc ( stdin )

Example:
1. Enter characters from the keyboard and save them to disk files one by one until '#' is entered

#include <stdio.h>
#include <stdlib.h>
int main(){
    
    
	//FILE *fp 是声明,声明fp是指针,用来指向FILE类型的对象。
	FILE *fp;
	char ch,filename[10];
	printf("请输入文件名称:\n");
	scanf("%s",filename);
	if((fp=fopen(filename,"w"))==NULL){
    
    
		printf("open file is false,exit...\n");
		exit(0);
	}
	printf("open file is true,Please input word\n");
	//前面的scanf()在读取输入时会在缓冲区中留下一个字符'\n'
    //所以如果不在此加一个getchar()把这个回车符取走的话,
	//而是会直接取走这个“无用的”回车符,从而导致读取有误。
	ch=getchar();
	//首次获取键盘输入
	ch=getchar();
	while(ch!='#'){
    
    
		//fputc 将字符ch写到文件指针fp所指向的文件的当前写指针的位置
		fputc(ch,fp);
		ch=getchar();
	}
	fclose(fp);
	return 0;
}

Input:
file1.c
computer and c#
Output:
computer and c
2. Copy information from one disk file to another disk file

#include <stdio.h>
#include <stdlib.h>
int main()
{
    
    
    FILE *in,*out;
	char ch,infile[10],outfile[10];
	printf("enter the infile name:");
	scanf("%s",infile);
	printf("enter the outfile name:");
	scanf("%s",outfile);
	if((in=fopen(infile,"r"))==NULL){
    
    
        printf("cannot open this file\n");
        exit(0);
	}
	if((out=fopen(outfile,"w"))==NULL){
    
    
        printf("cannot open this file\n");
        exit(0);
	}
	ch=fgetc(in);
	// 对feof()来说,站在光标所在位置,向后看看还有没有字符。如果有,返回0;如果没有,返回非0。
	//它并不会读取相关信息,只是查看光标后是否还有内容。
	//
	while(!feof(in)){
    
    
	    fputc(ch,out);
		ch=fgetc(in);
	}
	fclose(in);
	fclose(out);
	return 0;
}

Input:
file1.c
file2.c

10.4.2 fread function and fwrite function

Data block I/O: fread and fwrite
function prototypes:

size_t fread( void *buffer, size_t size, size_t count, FILE *fp)
size_t fwrite( void *buffer, size_t size, size_t count, FILE *fp)

*buffer, size_t: point to the first address of the data block to be input/output
size, size_t: the size (number of bytes) of each data block to be read/written
count, FILE: the number of data blocks to be read/written
* fp: the file pointer to be read/written
Function: read and write data blocks
Return value: success, returns the number of blocks read and written; error or end of file, returns 0

Example: Input the data of 4 students from the keyboard, save it to a disk file, and display it on the screen

#include <stdio.h>
#define SIZE 4
struct Student_type
{
    
    
	char name[10];
	int num;
	int age;
	char addr[15];
}stud[SIZE];
void save()
{
    
    
	FILE *fp;
	int i;
	if ((fp = fopen("stu_data", "wb")) == NULL)
	{
    
    
		printf("cant open file\n");
		return;
	}
	for (i = 0; i < SIZE; i++)
	{
    
    
		if (fwrite(&stud[i], sizeof(struct Student_type), 1, fp) != 1)
			printf("file write error\n");
	}
	fclose(fp);
}
void display()
{
    
    
	int i;
	FILE *fp;
	if ((fp = fopen("stu_data", "rb")) == NULL)
	{
    
    
		printf("cannot open file\n");
		return;
	}
	for (i = 0; i < SIZE; i++)
	{
    
    
		fread(&stud[i], sizeof(struct Student_type), 1, fp);
		printf("%-10s %4d %4d %-15s\n", stud[i].name, stud[i].num, stud[i].age, stud[i].addr);
	}
	fclose(fp);
}
int main()
{
    
    
	int i;
	printf("please enter date of studnet:\n");
	for (i = 0; i < SIZE; i++)
	{
    
    
		scanf("%s %d %d %s", stud[i].name, &stud[i].num, &stud[i].age, stud[i].addr);
	}
	save();
    display();
}

10.4.3 fprintf function and fscanf function

Formatted I/O: fprintf and fscanf
function prototypes:

int fprintf ( FILE *fp, const char  *format [argument...])
int fscanf ( FILE *fp,const char  *format [address...] )

Function: perform I/O operations on files according to the format
Return value: success, return the number of I/O; failure, error or end of file, return EOF

fprintf (fp, "%d,%6.2f",i,t);
//将i和t按%d,%6.2f格式输出到fp文件
fscanf(fp, "%d,%f",&i,&t);
//将文件中的整型数据输入i,浮点型数据输入t

10.4.4 Other read and write functions

String I/O: fgets and fputs

char *fgets( char *s, int n,FILE *fp)
int fputs(char *s,FILE *fp)

Function: Read and write a string from the file pointed to by fp
Return value:
fgets returns the first address of the read string when it is normal; returns NULL if it is an error or the end of the file;
fputs returns the last character written when it is normal; EOF is an error

fgets reads n-1 characters from the file pointed to by fp and sends them to the memory area pointed to by s, and adds '\0' at the end (if a newline character or end of file (EOF) is encountered before reading n-1 characters, that is end)
fputs writes the string pointed to by s to the file pointed to by fp

10.5 Location of files

10.5.1 rewind function

File position pointer ----- pointer to the current read and write position
Sequential read and write: the position pointer moves according to the order of the byte position
Random read and write: the position pointer moves to any position as required Function
prototype:

void rewind(FILE *fp)

Function: Reset the file position pointer to the beginning of the file
Return value: None

Example: From a file, display its contents on the screen for the first time and copy it to another file

#include<stdio.h>
int main()
{
    
    
    FILE *fp1,*fp2;
    fp1 = fopen("file1.c","r");
    fp2 = fopen("file2.c","w");
    while(!feof(fp1)) putchar(getc(fp1));
    rewind(fp1);
    while(!feof(fp1)) putc(getc(fp1),fp2);
    fclose(fp1);
    fclose(fp2);
}

10.5.2 fseek function and random reading and writing

fseek function
function prototype:

int fseek(FILE *fp, long offset, int from)

Function: change the position of the file position pointer
Return value: success, return 0; failure, return non-0;
offset: displacement, type is long, indicating the relative value (number of bytes) of the moving amount starting from from.
from: The starting position of the movement.
from value meaning:

from value Hirona meaning
0 SEEK_SET file header
1 SEEK_CUR current location
2 SEEK_END end of file

Example 1: There are 4 student data on the disk file, and it is required to read the 1st and 3rd student data and display them

#include <stdio.h>
#include<stdlib.h>
struct student_type
{
    
        char name[10];
     int num;
     int age;
     char addr[15];
}stud[10];
int main()
{
    
    
    FILE * fp;
    int i;
    if ((fp = fopen( "stu_data" , "rb" )) == NULL)
    {
    
    
    printf( "cannot open file\n " );
    exit(0);
    }
    for (i = 0 ;i < 4;i ++ )
    {
    
    
        fseek(fp,i*sizeof(struct student_type),0);
        fread(&stud[i],sizeof(struct student_type),1,fp);
        printf("%s %d %d %s \n",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
    }
    fclose(fp);
}

Example 2:

fseek(fp,10L,SEEK_SET);   //将读写指针移动到离文件头10个字节处
fseek(fp,20L,1);  //将读写指针移动到离当前位置20个字节处
fseek(fp,-10L,2);   //将读写指针移动到离文件末尾处10个字节处。

10.5.3 ftell function

Function prototype:

long ftell(FILE *fp)

Function: return the current position of the position pointer (indicated by the displacement relative to the beginning of the file)
return value: success, return the current position pointer position; fail, return -1L

10.6 Error detection

10.6.1 ferror function

Function prototype:

int  ferror(FILE  *fp)

Function: test whether there is an error in the file
Return value: no error, 0; error, non-0

Note:
1) Every time the file input and output function is called, a new ferror function value is generated, so it should be tested in time
2) When fopen opens the file, the initial value of the ferror function is automatically set to 0

10.6.2 clearerr function

Function prototype:

 void  clearerr(FILE  *fp)

Function: Set the file error flag to 0
Return value: None
Explanation: After an error occurs, the error flag remains until clearerr (fp) or rewind or any other input/output function is called on the same file

10.6.3 feof function

Function:
feof() is a function to detect the end of file on the stream, if the file ends, it returns a non-zero value, otherwise it returns 0

EOF:
1) EOF is a computer term, an acronym for End Of File, which means in the operating system that the data source has no more data to read. Data sources are often referred to as files or streams. This character is usually present at the end of the text to indicate the end of the material.
2) There is a hidden character "EOF" at the end of the document. When the program reads it, it will know that the file has reached the end.
3) The value of EOF is usually -1, but it varies according to the system.

The principle of feof():
stand at the position of the cursor and look backward to see if there are any characters. If there is, return 0; if not, return non-zero. It doesn't read the relevant information, it just checks to see if there is content after the cursor.

Note:
1) For a file, whether it is an empty file or a file with information, when the file is opened and the cursor is at the default beginning, there will be information after the cursor. At this time, call feof() to check whether the cursor is Content is meaningless.
2) We need to find the difference from the same, first use getc() to read a character from the file, and move the cursor one character backward. At this time, the cursor of the space-time file has moved to the back of EOF, and feof() will return 1 at this time. This is the correct usage of feof().
3) But pay attention, you must return the cursor to the beginning of the file, because before judging whether the file is empty, the cursor was moved forward one bit, and the cursor must be restored to the beginning, so as to ensure the normal reading of the file .

rewind(p);//将光标跳回到文件开头
Classification Function name
open a file fopen()
close file fclose()
file location fseek() ; rewind() ; ftell()
file read and write fgetc() , getc() , fputc() , putc() , fgets() , fputs() , getw() , putw() , fread() , fwrite() , fscan() , fprintf()
file status feof() , ferror() , clearerr()

Guess you like

Origin blog.csdn.net/qq_43310387/article/details/124245804