Easily learn C language Chapter 10 files

 

C language file operation

①C file overview ②File type pointer ③File opening and closing ④File reading and writing ⑤File positioning ⑥Error detection ⑦File input and output summary

Learning objectives of this chapter

  1. Understand the difference between text files and binary files;
  2. Understand the FILE *fp file pointer;
  3. Can use functions fopen and fclose to open and close files;
  4. Master the commonly used file read/write functions;

10.1 Overview of C files

File: A collection of data stored on external media, which is the unit of operating system data management.

Purpose of using data files

1. The change of the data file does not cause the change of the program-the program is separated from the data.

2. Different programs can access the data in the same data file-data sharing.

3. It can save the intermediate data or result data of the program running for a long time.

File classification

According to the logical structure of the file:

  1. Record file: composed of records with a certain structure (fixed length and variable length)
  2. Streaming file: consists of a character (byte) data sequence

By storage medium:

  1. Common files: storage media files (disks, tapes, etc.)
  2. Device files: non-storage media (keyboard, monitor, printer, etc.)

According to the organization of data:

  1. Text file: ASCII file, each byte stores the ASCII code of one character
  2. Binary file: the data is stored as it is in the memory form

C language files are streaming files.

The so-called stream is a series of bytes or characters. The start and end of the input and output data stream are only controlled by the program, not by the physical symbols (such as carriage returns). Such files are called streaming files.

Text file characteristics: large storage capacity, slow speed, easy to operate on characters

Binary file characteristics: small storage capacity, fast speed, easy to store intermediate results

The difference between text files and binary files:

① Computer storage is physically binary, so the difference between text files and binary files is not physical, but logical. The two are only different in the coding level.

②Binary stream saves space than text stream, and there is no need to convert \n, which can greatly speed up the stream and improve efficiency. Therefore, for a digital stream containing a large amount of digital information, the binary stream can be used; for a stream containing a large amount of character information, the text stream can be used.

③Text files are files based on character encoding. Common encodings include ASCII encoding, UNICODE encoding, and so on.

Binary files are files encoded based on values.

File processing method

  1. Buffer file system: Advanced file system, the system automatically opens up a memory buffer for the files in use. Can reduce the number of frequent data exchanges between the host and external devices
  2. Unbuffered file system: low-level file system, the user sets the buffer for each file in the program

10.2 File type pointer

File structure type FILE

The buffer file system creates a file information area in the memory for each file being used. The file information is described by a structure named FILE defined by the system

Define file type variables

Store file information

Such as: define an array of FILE type to store several file information: FILE f[5];

Define the file pointer variable, point to the FILE type structure variable, access the file through the file information in the structure variable.

Such as: FILE *fp;

usage:

When the file is opened, the system automatically creates the file structure and returns the pointer to it. The program obtains file information through this pointer and accesses the file

如:fp=fopen("a1","r");

After the file is closed, its file structure is released

The defined file pointer can be used to point to a file!

10.3 File opening and closing

C file operations are implemented with library functions, included in stdio.h

File usage: open file → file read/write → close file

The system automatically opens and closes three standard files:

  1. Standard input------keyboard stdin
  2. Standard output------display stdout
  3. Standard error output-----display stderr

1. Open the file (fopen function)

Function prototype: FILE *fopen(char *name,char *mode)

Calling method: fopen("file name","using file method")

例:FILE *fp;fp=fopen("d:\\user\\myfile.txt","r");

Return value: Open normally, return a pointer to the file structure; open failed, return NULL 

FILE   *fp;
fp=fopen(“aa.c","w");
if(fp==NULL)
{ 
   printf("File open error!\n");
   exit(0);     /*关闭所有文件终止调用*/
}

r: reading method;

w: writing method;

a: append method;

rb/wb/ab: Binary mode;

+: both readable and writable

2. Close the file (fclose function)

Function: Make the file pointer variable and the file "disconnect", release the file structure and file pointer

FILE  *fp;

fp=fopen(“a.txt”,“r”);

fclose(fp);

Return value: used to indicate whether the file is closed correctly, if the file is closed successfully, the value is 0, otherwise it is -1 (EOF).

The return value can be tested with the ferror function

10.4 File reading and writing

After the file is opened, it can be read and written.

Read/write a character in the file

1.fputc function (putc function)

Function prototype: int fputc(int c, FILE *fp)

Function: write one byte code c into the file pointed to by fp

Return value: normal, return c; error, EOF (-1)

2.fgetc function (getc function)

Function prototype: int fgetc(FILE *fp)

Function: read one byte code from the file pointed to by fp

Return value: return the code value read; EOF (-1) is read to the end of the file or error

3.feof function

Calling method: feof(fp)

Function: To judge whether the file is over when reading a binary file.

Return value: if it reaches the end of the file, it is true (non-zero) 

Text file:  end is true, non-zero  

//二进制或文本文件:
#include "stdio.h"
void main()
{ 
	FILE  *fp; 
	char ch;
	fp=fopen("d2.dat","r"); //fopen("文件路径","文件操作");
	ch=fgetc(fp);
	while(ch!=EOF)
	{ 
	 putchar(ch);
	 ch=fgetc(fp);
	}
	fclose(fp);
}

 

Binary or text file:

//二进制或文本文件:

#include "stdio.h"
void main()
{
    FILE  *fp;
    char ch;
    fp=fopen("d2.dat","r");
    ch=fgetc(fp);
    while(!feof(fp))
    {
        putchar(ch);
        ch=fgetc(fp);
    }
    fclose(fp);
}

Enter some characters from the keyboard and send them to the disk one by one until a "#" is entered.

//从键盘输入一些字符,逐个把它们送到磁盘上去,直到输入一个“#”为止。
#include <stdio.h>
#include <stdlib.h>
void main(){
	FILE *fp;
	char ch,filename[10];
	scanf("%s",filename);
	if((fp=fopen(filename,"w"))==NULL){
		printf("cannot open file \n");
		exit(0);//终止程序
	}
	ch = getchar();//接收执行scanf时最后输入的回车符
	ch = getchar();//第一个输入的字符被赋给变量ch
	while(ch!='#'){
		fputc(ch,fp);//字符被写入filename表示的文件中
		putchar(ch); //字符被输出到显示器
		ch = getchar();
	}
	putchar(10);//向屏幕输出一个换行符
	fclose(fp); //关闭文件
}

flow chart:

 

Example Copy the information in one disk file to another disk file.

//将一个磁盘文件中的信息复制到另一个磁盘文件中。
#include <stdio.h>
#include <stdlib.h>
void main(){
	FILE *in,*out;
	char ch,infile[10],outfile[10];
	printf("Enter the infile name:\n");
	scanf("%s",infile);
	printf("Enter the outfile name:\n");
	scanf("%s",outfile);
	if((in=fopen(infile,"r"))==NULL){
		printf("Cannot open infile.\n");
		exit(0);
	}
	if((out=fopen(outfile,"w"))==NULL){
		printf("Cannot open outfile.\n");
		exit(0);
	}
	//将infile的内容复制到outfile
	while(!feof(in))
		fputc(fgetc(in),out);
	fclose(in);
	fclose(out);
}	

Example Use the main parameter to enter two file names together when entering the command line. 

#include <stdio.h>
#include <stdlid.h>
void main(int argc,char *argv[ ])
{ 
	FILE *in, *out;
    char ch;
    if(argc!=3)
     { 
		printf("You forgot to enter a filename\n");
        exit(0); 
	}
  
	if((in = fopen(argv[1], "r"))== NULL)
    { 
		printf("Cannot open infile.\n");
        exit(0);  
	}
    if ((out = fopen(argv[2], "w"))== NULL)
    { 
		printf("Cannot open outfile.\n");
        exit(0);  
	}
    while (!feof(in))  
		fputc(fgetc(in), out);
    fclose(in);   
	fclose(out);  
}

When the executable file name is: a.exe, enter the command line: C:\>a file1.c file2.c then: copy the contents of file1 to file2

Data block input and output functions:

4. The general call form of fread and fwrite:

  • fread(buffer,size,count,fp );
  • fwrite(buffer,size,count,fp );

Parameter Description:

  1. buffer: The storage first address of the data block to be read or the start address of the data block to be output .
  2. size: The size (number of bytes) of each data block to be read/written
  3. count: the number of data blocks to be read/written
  4. fp: File pointer to be read/written. Return value: success, return the value of count; error or end of file, 0 value.

fread and fwrite are generally used for the input/output of binary files. If the file is opened in binary form, any type of data can be read and written with fread or fwrite .

Such as: fread(f, 4, 2, fp)

Example Input the data of 4 students from the keyboard, then save it to the disk, and display the contents of the disk file 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 main()
{ 
	void save();
	void display();
	int i;
	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(); 
}
void save()
{ 
	FILE *fp;
	int  i;
	// 文件必须是以“二进制”打开的,
	if((fp=fopen("d:\\stu_list","wb"))==NULL)
	{ 
	   printf("cannot 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()
{ 
	FILE *fp;
	int  i;
	if((fp=fopen("d:\\stu_list","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);
}

Functions for reading and writing files in the specified format:

5. The general calling format of fprintf and fscanf:

  1. fscanf(fp, format string, input list);
  2. fprintf(fp, format string, output list);

Return value: success, return the number of I/O; error or end of file, return EOF. Because input and output need to be converted from ASCII code to binary form, it takes more time.

fscanf( fp,"%d,%f",&i,&t); /*If there are 3, 4.5 in the file, then read 3 into i, 4.5 read into t*/

fprintf(fp,"%d,%6.2f",i,t); /*Write i and t to fp file in %d, %6.2f format*/

void save()
{  
   FILE *fp;
   int  i;
   if((fp=fopen("d:\\stu_list","w"))==NULL)
   { 
        printf("cannot open file\n");
        return;
   }
   for(i=0;i<SIZE;i++)
      fprintf(fp,"%s %d %d %s",stud[i].name,
            stud[i].num,stud[i].age,stud[i].addr);
   fclose(fp);
}
void display()
{ 
   FILE *fp;
   int  i;
   if((fp=fopen("d:\\stu_list","r"))==NULL)
   { 
       printf("cannot open file\n");   return;}
       for(i=0;i<SIZE;i++)
       { 
           fscanf(fp,"%s %d %d %s",stud[i].name,
                   stud[i].num,stud[i].age,stud[i].addr);         
           printf("%-10s %4d %4d %-15s\n",stud[i].name,
                   stud[i].num,stud[i].age,stud[i].addr);
       }
       fclose(fp);
    }
}

Other read and write functions

6. putw and getw functions

Function: In binary form, read and write an int type integer to the disk file, 2 bytes.

Return value: success: the integer value written; failure: EOF.            

Such as: putw(10,fp);                  

 i=getw(fp);

7.fgets and fputs functions

form:

fgets(str,n,fp);   (str character array, n-1 characters)                

fputs(string, fp); ("\0" is not output)

Role: read/write a string from the file pointed to by fp

Return value: fgets returns the first address of the string when it is normal; error or the end of the file, NULL fputs returns the last character written when it is normal; error is EOF

Example Read a character string from the keyboard and store it in a file, and then read it back from the file to display

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{ 
	FILE  *fp;
	char  string[81];
	if((fp=fopen("1.txt","w"))==NULL)
	{ 
		printf("cann't open file");
		exit(0); 
	}
	while(strlen(gets(string))>0)
	{ 
		fputs(string,fp);
		fputs("\n",fp); 
	}
	fclose(fp);
	if((fp=fopen("1.txt","r"))==NULL)
	{ 
		printf("cann't open file");
		exit(0); 
	}
	while(fgets(string,81,fp)!=NULL)
	   fputs(string,stdout);
	fclose(fp); 
}

10.5 File location

Several concepts

File position pointer-----pointer to the current reading and writing position, the specific position is determined by the file opening method.

  • "R" "w": point to the file header
  • "A": point to the end of the file

Read and write method

  • Sequential reading and writing: The position pointer moves in the order of byte position.
  • Random reading and writing: The position pointer can be moved to any position as needed.

1.rewind function

Function prototype: void rewind(FILE *fp)

Function: reset the file position pointer to the beginning of the file

Return value: None

Example of displaying and copying a disk file twice

#include <stdio.h>
void main()
{ 
   FILE *fp1,*fp2;
   fp1=fopen("c:\\tc\\user\\ch12_4.c","r");
   fp2=fopen("d:\\tc\\user\\ch12_41.c","w");
   while(!feof(fp1))  
       putchar(getc(fp1));
   rewind(fp1);
   while(!feof(fp1))  
       putc(getc(fp1),fp2);
   fclose(fp1);   
   fclose(fp2);
}

2. fseek function and random read and write

Call form: fseek (file type pointer, displacement, starting point)

Function: Change the position of the file position pointer

Return value: success, return 0; failure, return non-zero value

Example There are 10 student data in the file, input the singular student data into the computer and display it on the screen

#include <stdlid.h>
#include <stdio.h>
struct student_type
{ 
   char name[10];
   int num;
   int age;
   char sex;
}stud[10];

void main()
{ 
   FILE *fp;
   int  i;
   if((fp=fopen("stud_dat","rb"))==NULL)
   { 
       printf("cannot open file\n");  
       exit(0);
   }
   for(i=0;i<10;i+=2)
   { 
       fseek(fp,i*sizeof(struct student_type),0);//
       fread(&stud[i],sizeof(struct student_type), 1,fp);
       printf("%s %d %d %c\n",stud[i].name,stud[i].num,
                    stud[i].age,stud[i].sex);
   }
   fclose(fp);
}

3.ftell function

Function prototype: long ftell(FILE *fp)

Function: Get the current position of the position pointer in the streaming file (indicated by the displacement relative to the beginning of the file)

Return value: return the current position pointer position; fail, return -1L

//例  求文件长度
#include"stdio.h"
void main()
{ 
	FILE *fp;
	char filename[80];
	long length;
	gets(filename);
	fp=fopen(filename,"rb");
	if(fp==NULL)
	   printf("file not found!\n");
	else
	{ 
		fseek(fp,0L,SEEK_END);
	    length=ftell(fp);
	    printf("Length of File is %1d bytes\n",length);
	    fclose(fp);  
	}
}

10.6 Error detection

1.ferror function:

  • Test file for errors
  • Calling form: ferror(fp);
  • Return value: no error, 0; error, not 0
  • Explain that every time the file input and output function is called, a new ferror function value is generated, so it should be tested in time when fopen opens the file, the initial value of the ferror function is automatically set to 0

2.clearerr function

Calling form: clearerr(fp);

Function: Set the file error flag to 0, no return value.

Note: After an error occurs, the error flag remains until clearerr(fp) or rewind or any other input and output function is adjusted for the same file

例   ferror()与clearerr()举例
#include <stdio.h>
int  main(void)
{ FILE *stream;
   stream = fopen("DUMMY.FIL", "w");
   getc(stream);
   if (ferror(stream))
     { printf("Error reading from DUMMY.FIL\n");
        clearerr(stream);
     }
   if(!ferror(stream))
       printf("Error indicator cleared!");
   fclose(stream);
   return 0;
}

10.7 Summary of file input and output

  1. When using a file, you must first define a file pointer:
  2. FILE *fp; Then use the pointer to manipulate the corresponding file;
  3. Through the function fopen, the file pointer fp is connected with the corresponding file, and the connection between fp and the file is cut off through the fclose function;
  4. The file can be opened in text mode (default or "t"), or in binary mode ("b");
  5. If you process the file one character at a time, you need to use the fgetc or fputc function;
  6. If you process the file one line at a time, you can use the function fgets or fputs;
  7. If you process files one structure at a time, you can use the functions fread and fwrite (mostly binary files);
  8. The fscanf and fprintf functions are widely used and should be mastered.

The notes in this article are from the PPT of C program design by Tan Haoqiang, I love learning haha!

If you think the writing is good, please like it~

Guess you like

Origin blog.csdn.net/weixin_41987016/article/details/105879508