当前位置:网站首页>C language file operation

C language file operation

2022-06-11 00:03:00 ღ ° Jiusan ฅ ՞

One 、 Opening and closing of files

  • FILE * fopen ( const char * filename, const char * mode ); —> Open file , The second parameter mode It's read-write mode
  • After use , You also need to close the file :int fclose ( FILE* stream);
#include <stdio.h>
int main ()
{
    
	  FILE * pFile;
	  // Open file 
	  pFile = fopen ("myfile.txt","w");
	  if (pFile==NULL)
	  {
    
	 		//  fail to open file , Unable to operate 
	 		printf("pFile is fail\n");
	 		return 0;
	  }
	  // pFile Successfully point to a valid file information area , File operation is available  
	  fputs ("fopen example",pFile);
	  // Close file 
      fclose (pFile);
	  return 0;
}

Common reading and writing modes mode

Pattern meaning If the specified file does not exist
“r”( read-only ) To enter data , Open one Already exist Text file for error
“w”( Just write ) To output data , Open a text file Automatically create files
“a”( Additional ) Append data to the end of the text file Automatically create files
“rb”( read-only ) To enter data , Open a binary file error
“wb”( Just write ) To enter data , Open a binary file Automatically create files
“ab”( Additional ) Add data to the end of a binary file error

Two 、 Sequential reading and writing of files

All flows : Handle file out of stream , The computer will open three streams by default every time it is turned on and running , It is called standard flow .

  • stdout - Standard output stream
  • stdin - Standard input stream
  • stderror - Standard error flow

fgetc And fputc

  • fgetc - character Input function , For all streams int fgetc( FILE *stream );
  • fputc - character Output function , For all streams int fputc( int c, FILE *stream );

Code display

// fgetc And fputc
int main()
{
    
	//  Open file 
	FILE* pf = fopen("data.txt", "r");
	if (pf == NULL)
	{
    
		//  Open the failure 
		printf("%s\n", strerror(errno));
		return 0;
	}

	//  Working with files 
	/*int ch = 'a'; for (ch = 'a'; ch <= 'z'; ch++) { fputc(ch, pf); }*/
	for (int i = 0; i < 26; i++)
	{
    
		int ch = fgetc(pf);
		printf("%c", ch);
	}
	printf("\n");

	//  Close file 
	fclose(pf);

	return 0;
}

fputc take 26 Write a letter to the file
 Insert picture description here
fgetc Read character by character in the file
 Insert picture description here

fgets And fputs

Be careful : When I was studying, I always thought fputs Is to write a sentence on one line , and fgets Read a line ; Actually fputs It's direct writing , and fgets It is on demand , The number of incoming reads is required

  • fgets - Text line input function , For all streams char *fgets( char *string, int n, FILE *stream ); - The return is string The address of ( From a stream Read in the stream n Characters to string in )
  • fputs - Text line output function , For all streams int fputs( const char *string, FILE *stream );( Write a string to stream In the stream )

Code display

// fgets And fputs
int main()
{
    
	//  Open file 
	FILE* pf = fopen("data.txt", "r");
	if (pf == NULL)
	{
    
		//  Open the failure 
		printf("%s\n", strerror(errno));
		return 0;
	}

	//  Working with files 
	/*fputs("hello world\n", pf); fputs("I Love You\n", pf);*/
	char arr[100] = {
     0 };
	fgets(arr,10,pf);
	printf("%s\n", arr);

	//  Close file 
	fclose(pf);

	return 0;
}

fputs - Write two sentences
 Insert picture description here
fgets - Reading data
 Insert picture description here

fscanf And fprintf

For formatted input and output

  • fscanf - Format input function , For all streams int fscanf( FILE *stream, const char *format [, argument ]... );
  • fprintf - Format output function , For all streams int fprintf( FILE *stream, const char *format [, argument ]...);

Code demonstration

// fprintf And fscanf
struct Stu
{
    
	char name[20];
	int age;
};

int main()
{
    
	struct Stu s = {
     "chen", 20 };
	struct Stu tmp = {
     0 };
	FILE* pf = fopen("data.txt", "r");
	if (pf == NULL)
	{
    
		printf("%s\n", strerror(errno));
		return 0;
	}

	//fprintf(pf,"%s %d\n", s.name, s.age);
	fscanf(pf, "%s %d", tmp.name, &(tmp.age));
	printf("%s %d\n", tmp.name, tmp.age);
	fclose(pf);

	return 0;
}

fprintf - Output a structure data to a file according to the format

 Insert picture description here

fscanf - Input the data in the file into the structure in a formatted form

 Insert picture description here

Comparison of a set of functions

printf( Print data to the screen )
  • int printf( const char *format [, argument]... ); - towards stdout Function to format the output
scanf( Get data from the keyboard )
  • int scanf( const char *format [,argument]... ); - from stdin Format the input function
fprintf( Print data to a file ,stream = stdout when , amount to printf)

 Insert picture description here

fscanf( Get data from files ,stream = stdin when , amount to scanf)

 Insert picture description here

sprintf( Convert data to strings )

 Insert picture description here

sscanf( Converts the contents of a string to a specified format )

 Insert picture description here

sscanf And sprintf Code demonstration

struct Book
{
    
	char name[20];
	double price;
};

int main()
{
    
	struct Book book = {
     "C Programming ", 66.6 };
	struct Book tmp = {
     0 };
	char arr[100] = {
     0 };

	 sprintf(arr, "%s %lf", book.name, book.price);
	 printf("%s\n", arr);

	sscanf(arr, "%s %lf", tmp.name, &(tmp.price));
	printf("%s %lf\n", tmp.name, tmp.price);

	return 0;
}

 Insert picture description here

fread And fwrite

  • fread - Binary input , Only for files size_t fread( void *buffer, size_t size, size_t count, FILE *stream ); - take stream The contents of the file stream are input into buffer In the variable at address , Every time you type count individual size The contents of the number of bytes ; Return value : The number of contents actually written ( It also uses a number to judge whether it is over )
  • fwrite - Binary output , Only for files size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream ); - take buffer The content at the address is entered into stream In file stream , Every time you type count individual size The contents of the number of bytes ; Return value : The number of contents actually output to the file ( It also uses a number to judge whether it is over )

Code display

// fread And fwrite
#include <stdio.h>
int main()
{
    
	int a = 10000;
	int c = 0;
	FILE* pf = fopen("test.txt", "rb");
	if (pf == NULL)
		return 0;
	// fwrite(&a, 4, 1, pf);// The binary form is written to the file 
	fread(&c, 4, 1, pf);
	printf("%d\n", c);

	fclose(pf);
	pf = NULL;
	return 0;
}

fwrite
 Insert picture description here
fread
 Insert picture description here

3、 ... and 、 Random reading and writing of documents

fseek

according to The position of the file pointer and Offset To locate the file pointer

  • int fseek ( FILE * stream, long int offset, int origin );
  • offset - Offset ( Positive numbers go backwards , Negative numbers go forward )
  • origin - The starting position of the file offset
    • SEEK_CUR - Current pointer position
    • SEEK_END - end of file
    • SEEK_SET - Beginning of file

 Insert picture description here

ftell

Returns the offset of the file pointer from its starting position

  • long int ftell ( FILE * stream );

 Insert picture description here

rewind

Return the file pointer to the beginning of the file

  • void rewind ( FILE * stream );
  • Same effect fseek Realization :fseek(FILE * stream,0,SEEK_CUR);

 Insert picture description here

Four 、 Simple comparison between text file and binary file

All characters are written in ASCII stored , Numerical data can be used either ASCII stored , It can also be stored in binary form . The following will demonstrate with numerical data storage

  • Binary : Data is stored in memory in binary form , If the output without conversion is to external memory
  • text file : If it's required to use ASCII In the form of code , You need to convert before storing . With ASCII Characters in the form of stored files

If there are integers 10000, If the ASCII Code output to disk , The disk is occupied by 5 Bytes ( One byte per character ), And binary output , On the disk 4 Bytes (VS2013 test ).

Binary storage

int main()
{
    
	int a = 10000;

	FILE* pf = fopen("test.txt", "wb");
	if (pf == NULL)
		return 0;

	fwrite(&a, 4, 1, pf); //  Write to file in binary form 
	
	fclose(pf);
	pf = NULL;

	return 0;
}

 Insert picture description here
 Insert picture description here
 Insert picture description here

File store

The contents are directly displayed as integers 10000

5、 ... and 、 Misused feof

  • int feof( FILE *stream );
  • feof() Is a function that detects the file terminator on the stream , If the file ends , Then return to non 0 value , Otherwise return to 0

Be careful :feof It is not used to judge whether the file is finished , But to judge why it ended (1. Read failed ,2. Read to the end of the file )

text file

  • Whether the reading of text file is finished , Determine whether the return value is EOF ( fgetc ), perhaps NULL ( fgets )
int main()
{
    
	int c; //  Be careful : To judge EOF, Need to use int
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
    
		printf("File opening failed");
		return 0;
	}
	//fgetc  When reading fails or the end of the file is encountered , Will return to EOF
	while ((c = fgetc(pf)) != EOF)
	{
    
		fputc(c, stdout);
	}

	//  Judge why it ended 
	if (feof(pf))
	{
    
		printf("End of file reached successfully");
	}
	else
	{
    
		printf("error when reading");
	}

	fclose(pf);
	pf = NULL;

	return 0;
}

Binary

#include <stdio.h>
int main()
{
    
	int a = 10000;
	int c = 0;
	FILE* pf = fopen("test.txt", "rb");
	if (pf == NULL)
		return 0;

	while (fread(&c, 4, 1, pf))
	{
    
		printf("%d\n", feof(pf));
	}
	printf("%d\n", feof(pf));
	if (feof(pf))
		printf("End of file reached successfully\n");
	else
		printf("error when reading\n");

	fclose(pf);
	pf = NULL;
	return 0;
}

 Insert picture description here

6、 ... and 、 File buffer

What is a file buffer

ANSIC The standard puts forward “ File buffer system ”, The so-called buffered file system means that the system automatically creates files for programs in memory Open up a block for each file in use “ File buffer ”. Data output from memory to disk is first sent to a buffer in memory , After the buffer is filled, it is sent to the disk together . If you read data from disk to computer , Then read the data from the disk file and input it into memory Impact area ( Fill the buffer ), And then send the data from the buffer to the program data area one by one ( Program variables, etc ). Before full , Flusheable buffer , Let it force output , Input . The size of the buffer is designed by the compiler vendor

 Insert picture description here

  • Be careful : stay Linux The buffer effect can be better seen in
#include <stdio.h>
#include <windows.h>
//VS2013 WIN10 Environmental testing 
int main()
{
    
	FILE* pf = fopen("test.txt", "w");
	fputs("abcdef", pf);// Put the code in the output buffer first 
	printf(" sleep 10 second - The data has been written , open test.txt file , Found no content in the file \n");
	Sleep(10000);
	printf(" Refresh buffer \n");
	fflush(pf);// When the buffer is flushed , Write the data in the output buffer to a file ( disk )
	// notes :fflush  In high version VS It can't be used on 
	printf(" Sleep again 10 second - here , Open again test.txt file , There's something in the file \n");
	Sleep(10000);
	fclose(pf);
	// notes :fclose When closing a file , It also flushes the buffer 
	pf = NULL;
	return 0;
}

Conclusion

Because there is a buffer ,C Language when operating files , You need to flush the buffer or close the file at the end of the file operation Pieces of . If you don't do , May cause problems in reading and writing files .

The meaning of the buffer

  1. Process the instructions entered by the user together Than Character by character processing Less consumption
  2. When the user is typing , Input error , Changeable , Enter and execute , Better user experience

Buffer classification

C Languages use different buffers in different places as needed .
Buffers are divided into two categories : Completely buffered I/O And line buffering I/O And without buffering .
(1) Full buffering means that the buffer is refreshed only when the current buffer is full ( The content is sent to the destination ), It usually appears in file input . The size of the buffer depends on the system , The common size is 512 Byte and 4096 byte .
(2) Line buffering refers to refreshing the buffer when a line break occurs . Keyboard input is usually line buffered input , So press Enter Key to refresh the buffer . A common example is getchar() function , When the program calls getchar() Function time , The program is waiting for the user to press the button , The characters entered by the user are stored in the keyboard buffer , Until the user presses enter ( The carriage return character is also placed in the buffer ). When the user types enter ,getchar() Function starts reading one character at a time from the keyboard buffer . in other words , Follow up getchar() Function calls do not wait for the user to press a key , And read the characters in the buffer directly , Until the characters in the buffer are read , Just wait for the user to press the key again . When the buffer is full, it will not be refreshed automatically and input cannot continue , Press enter to refresh the buffer .
(3) Without buffer : Standard output without buffer ( for example :cerr
(4) Buffer refresh ( Carry out the real I/O operation )
When the buffer is full : perform flush sentence ; perform end sentence ; Close file .

原网站

版权声明
本文为[ღ ° Jiusan ฅ ՞]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020932187726.html

随机推荐