当前位置:网站首页>018 basics of C language: C file reading and writing

018 basics of C language: C file reading and writing

2022-06-27 04:25:00 Prison plan progress 50%

One : summary

We are very familiar with the concept of document , For example, the common Word file 、txt file 、 Source files, etc . File is a kind of data source , The main function is to save data . In the operating system , In order to unify the operation of various hardware , Simplify the interface , Different hardware devices are also treated as one file . Operations on these files , Equivalent to the operation of ordinary files on disk . for example , The display is often referred to as a standard output file ,printf Is to output to this file , Call the keyboard a standard input file ,scanf Is to get data from this file .

The correspondence between common hardware devices and files

file Hardware device
stdin Standard input file , General keyboard ;scanf()、getchar() By default, functions such as stdin Get input .
stdout Standard output file , Generally refers to the display ;printf()、putchar() And so on. By default stdout Output data .
stderr Standard error file , Generally refers to the display ;perror() And so on. By default stderr Output data ( I'll talk about ).
stdprn Standard print files , Generally refers to the printer .

 

Two : File stream

All files are saved on disk , You have to load memory to process , All data must be written to a file ( disk ) It won't be lost . The process of transferring data between files and memory is called file stream , It's like water flowing from one place to another . The process of copying data from a file to memory is called an input stream , The process of saving from memory to a file is called output stream . therefore , We can say that opening a file means opening a stream .

 

3、 ... and : Opening of files

stay C In language , File operations are done by library functions .fopen Function is used to open a file FILE *fopen(char *filename, char *mode);

  • filename For the file name ( Include file path ),mode For open mode , They're all strings
  • fopen() Will get file information , Include the file name , File status , Current reading and writing position, etc , And save this information to a FILE In the structure variable of type , Then return the address of the variable to .
  • FILE Is in stdio.h A structure defined in the header file , Used to save file information .

If you need to receive fopen() The return value of , You need to define a FILE Pointer to type . for example :FILE *fp = fopen("demo.txt", "r");
Said to “ read-only ” Open... In the current directory demo.txt file , And make fp Point to the file , So you can get through fp To operate demo.txt 了 .fp It is often called a file pointer .

Open mode mode There are many kinds of :

 Open mode 				 explain 
r			 Open the file read-only , Read only , Not allowed to write . The file must exist .
r+			 Reading / Open file in write mode , Allow reading and writing . The file must exist .
rb+			 Reading / Write to open a binary file , Allow to read / Writing data .
rt+			 Reading / Write to open a text file , Allow reading and writing .
w			 Open the file in write only mode , If the file exists, the length is 0, That is, the content of the file disappears , If not, create the file .
w+			 Reading / Open file in write mode , If the file exists, the file length is clear to zero , That is, the contents of the file will disappear . If the file does not exist, create it .
a			 Open a write only file as an append . If the file does not exist , The file will be created , If the file exists , The data written will be added to the end of the file , That is, the original contents of the document will be preserved (EOF Fu reserved ).
a+			 Open readable by appending / Written documents . If the file does not exist , The file will be created , If the file exists , The data written will be added to the end of the file , That is, the original contents of the document will be preserved ( The original EOF operator   No reservation ).
wb			 Open or create a new binary file in write only mode , Only data is allowed to be written .
wb+			 Reading / Write to open or create a binary file , Allow reading and writing .
wt+			 Reading / Write to open or create a text file , Allow read and write .
at+			 Reading / Write to open a text file , Allow to read or append data at the end of text .
ab+			 Reading / Write to open a binary file , Allow reading or appending data to the end of a file .

Some notes :

  1. The file is opened by r/w/a/t/b/+ Six characters , What is the meaning of each character :
    r(read): read
    w(write): Write
    a(append): Additional
    t(text): text file , Omit not to write
    b(banary): Binary
    +: Read and write

  2. without “b” character , The file opens as text .

  3. All use “r” When opening a file , The file must already exist .

  4. When opening a file , If something goes wrong ,fopen Will return a null pointer value NULL. In the program, this information can be used to determine whether to complete the work of opening the file , And make corresponding treatment . Therefore, the following program is often used to open the file :

     if(fp = fopen("d:\\demo.txt", "rb") == NULL){
     	printf("error on open D:\\demo.txt file!");
     	getch();	//  The function of this statement is : Enter a character from the keyboard , But not on the screen . ad locum , The effect is to wait , Only when the user taps any key from the keyboard , The program continues . So users can use this waiting time to read the error prompt .
     	exit(1);
     }
    
  5. When reading a text file into memory , To put ASCII Code to binary code , When writing a file to disk as text , Also convert the binary code to ASCII code , So it takes a lot of time to read and write text files . There is no such conversion between reading and writing binary files .

  6. Standard input file stdin( keyboard )、 Standard output file stdout( Monitor )、 Standard error file stderr( Monitor ) It's opened by the system , Can be used directly .

 

Four : File close (fclose function )

Once the files are used , Should use the fclose() Function to close the file , To release resources , Avoid data loss .fclose() The prototype for :int fclose(FILE *fp);
fp Is a pointer file , for example :fclose(fp);
When the file is closed normally ,fclose() The return value of is 0, If a non-zero value is returned, an error has occurred .

 

5、 ... and : Read and write files

5.1: In the form of characters

5.1.1: summary

stay C In language , It's flexible to read and write files , You can read and write one character at a time , You can also read and write a string , Even any byte of data ( Data blocks ). When reading and writing files in character form , You can read one character at a time from the file , Or write a character to the file . There are two main functions :fgetc() and fputc()

5.1.2: Character reading function fgetc

fgetc yes file get char Abbreviation , It means to read a character from a specified file . Archetype :int fgetc (FILE *fp);

fp For file pointer .fgetc() When the read is successful, the character read is returned , Returns when reading to the end of the file or when reading fails EOF.

EOF yes end of file Abbreviation , Indicates the end of the file , Is in stdio.h Macro defined in , The value is a negative number , Tend to be -1. The reason why the return value type is int, Just to accommodate this negative number (char It can't be negative ).

fgetc() Use examples :
	char ch;
	FILE *fp = fopen("d:\\demo.txt", "r+");
	ch = fgetc(fp);
 From d:\\demo.txt Read a character in the file , And save it to the variable ch in .

There is a position pointer inside the file , Used to point to the current reading and writing position , That is, read and write the first few bytes . When the file is open , The pointer always points to the first byte of the file . Use fgetc After the function , The pointer moves back one byte , So it can be used many times in a row fgetc Read multiple characters .

Be careful : The location pointer inside this file is the same as C A pointer in a language is not the same thing . The position pointer is just a sign , Indicates where the file is read or written , That is, read and write the first few bytes , It doesn't mean the address . Every time a file is read or written , The position pointer will move once , It doesn't require you to define and assign values in the program , It's set automatically by the system , Transparent to users .

5.1.3: example

#include <stdio.h>
int main(){
    
	FILE *fp;
	char ch;
	//  If the file doesn't exist , Give a prompt and exit 
	if((fp=fopen("d:\\demo.txt", "rt")) == NULL){
    				//  The three pairs of parentheses here cannot be less , Can not write :if(fp=fopen("d:\\demo.txt", "rt") == NULL){ 
		printf("cannot open file,press any key to exit!");
		getch();
		exit(1);
	}

	//  Read one byte at a time , Until the read is complete 
	while((ch = fgetc(fp)) != EOF){
    			//  There are three pairs of parentheses here , Or there will be reading garbled code , I don't know why 
		putchar(ch);
	}
	putchar('\n');      //  Output line breaks 
	fclose(fp);
	return 0;
}
 result :aaaaaaaaaaaaaaaaaaaaaabbbbbbbbb
	 stay D Create under disk demo.txt file , Enter anything and save , Run the program , You will see that all the contents you just entered are displayed on the screen .
	 The function of the program is to read characters one by one from the file , Show... On the screen , Until the read is complete .
	 Procedure No 14 Line is the key ,while  The condition of the cycle is (ch=fgetc(fp)) != EOF.fget()  Read one character at a time from the position of the position pointer , And save it to the variable  ch, The position pointer moves back one byte .
	 When the file pointer moves to the end of the file ,fget()  You can't read characters , So back  EOF, Indicates the end of file reading .

5.1.4: Yes EOF Explanation

EOF It means the end of the file , It means the end of the read , But a lot of functions also return when there is a reading error EOF, So when you go back EOF when , In the end is the file read or read error ? We can use stdio.h To determine , Namely feof() and ferror()

feof() Function to determine whether the pointer inside the file points to the end of the file , Its prototype is :
	inf feof(FILE *fp);		 When pointing to the end of the file , Returns a nonzero value , Otherwise return zero value .
ferror() Function to determine if there is an error in a file operation , Its prototype is :
	int ferror(FILE *fp);	 An error returned a non-zero value , Otherwise return zero value .

example :

#include <stdio.h>
int main(){
    
	FILE *fp;
	char ch;

	//  Judge whether the file exists 
	if((fp=fopen("d:\\demo.txt", "r+")) == NULL){
    
		printf("cannot found file, press any key to exit!");
		getch();
		exit(1);
	}
	//  Read one byte at a time , Until the read is complete 
	while((ch = fgetc(fp)) != EOF){
    
		putchar(ch);
	}
	putchar('\n');

	if(ferror(fp)){
    
		puts(" Read error ");
	}else{
    
		puts(" Read successful ");
	}
	fclose(fp);
	return 0;
}
 result :
	aaaaaaaaaaaaaaaaaaaaaabbbbbbbbb
	 Read successful 

5.1.5: Character write function fputc

fputc yes file output char Abbreviation , It means to write a character to the specified file . The form of the call is :int fputc(int ch, FILE *fp);

ch For the character to write ,fp For file pointer .fputc() Returns the written character when the write is successful , Return... On failure EOF, The return value type is int Also to accommodate this negative number .
for example ;

fputc('a', fp);
	 perhaps :
char ch = 'a';
fputc(ch, fp);
	 It means to put the character 'a' write in fp In the file pointed to .

Two points :

  1. The written file can be used to write 、 Reading and writing 、 Add mode on , When an existing file is opened in write or read-write mode, the contents of the original file will be cleared , And put the written characters at the beginning of the file . If you need to keep the original file content , And put the written characters at the end of the file , You have to open the file by appending . No matter how you open it , If the written file does not exist, the file will be created .
  2. Every character written , The file internal position pointer moves back one byte .

example :

#include <stdio.h>
int main(){
    
	FILE *fp;
	char ch;

	//  Judge whether the file is opened successfully 
	if((fp=fopen("d:\\demo.txt", "wt+")) == NULL){
    
		printf("cannot open file, press any key to exit! \n");
		getch();
		exit(1);
	}
	printf("input a string: \n");
	//  Read one character at a time from the keyboard and write to the file 
	while((ch=getchar()) != '\n' ){
    
		fputc(ch, fp);
	}
	fclose(fp);
	return 0;
}

 Run the program , Enter a line of characters and press enter to end , open D On the plate demo.txt file , You can see what you just entered .

 

5.2: In the form of strings

5.2.1: introduce

fgetc() and fputc() Function can only read and write one character at a time , Slower ; In actual development, it is often to read and write a string or a data block at a time , This can significantly improve efficiency .

5.2.2: Read string function fgets

fgets() Function is used to read a string from a specified file , And save it to the character array , Its prototype is :char *fgets(char *str, int n, FILE *fp);
str Is a character array ,n For the number of characters to read ,fp For file pointer .

Return value : Return the first address of character array when reading successfully , That is to say str; Returns when the read fails NULL; If the internal pointer of the file has already pointed to the end of the file when reading begins , Then you won't be able to read any characters , Also returned NULL

Be careful , Read the string will be automatically added at the end of ‘\0’,n One character also includes ‘\0’. in other words , Actually, it only reads n-1 Characters , If you want to read 100 Characters ,n The value of should be 101. for example :

#define N 101
char str[N];
FILE *fp = fopen("D:\\demo.txt", "r");
fgets(str, N, fp);
 From  D:\\demo.txt  Read from 100 Characters , And save it to the character array str in .

The point is , Reading into n-1 If there is a line break before characters , Or read to the end of the file , Then the end of reading . That means , No matter n What is the value of ,fgets() Only one line of data can be read at most , You can't cross the line .

stay C In language , There is no function to read files by line , We can use fgets(), take n The value of is set large enough , One line of data can be read at a time .

example :

#include <stdio.h>
#include <stdlib.h>
#define N 100
int main(){
    
	FILE *fp;
	char str[N+1];
	if((fp=fopen("d:\\demo.txt", "rt")) == NULL){
    
		printf("cannot found file, press any key to exit! \n");
		getch();
		exit(1);
	}

	while(fgets(str, N, fp) != NULL){
    
		printf("%s", str);
	}
	printf("\n");
	fclose(fp);
	system("pause");
	return 0;
}

fgets()  When it comes to line breaks , The newline character will be read into the current string . The output of this example is consistent with demo.txt bring into correspondence with , Where it's time to break lines , Because of fgets() Can read line breaks . and gets() Dissimilarity , It ignores line breaks .

5.2.3: Write string functions fputs

fputs() Function is used to write a string to the specified file , Its prototype is :int fputs(char *str, FILE *fp);
str For the string to be written ,fp For file pointer . Write success, return non negative number , Failure to return EOF.

for example :

char *str = "http:www.qq.com";
FILE *fp = fopen("d:\\demo.txt", "a++");
fputs(str, fp);
 Represents a string str Write to d:\\demo.txt In file 

example :

 Established in the example above d:\\demo.txt Append a string to the file 
#include <stdio.h>
int main(){
    
	FILE *fp;
	char str[102] = {
    0}, strTemp[100];
	if((fp=fopen("d:\\demo.txt", "at+")) == NULL){
    
		printf("cannot open file, press any key to exit! \n");
		getch();
		exit(1);
	}
	printf("input a string: ");
	gets(strTemp);
	strcat(str, "\n");
	strcat(str, strTemp);
	fputs(str, fp);
	fclose(fp);
	return 0;
}

 

5.3: Read and write files in the form of data blocks

fgets() There are limitations , At most one line can be read from the file at a time , because fgets End reading when a newline character is encountered . If you want to read multiple lines , Need to use fread function , Corresponding write function fwrite.

fread() Function to read block data from the specified file . Block data , That is, several bytes of data , It can be a character , It can be a string , It can be multi line data , There are no restrictions .

fread() Prototype :
	size_t fread(void *ptr, size_t size, size_t count, FILE *fp);
fwrite() The function is used to write block data to a file , Its prototype :
	size_t fwrite(void *ptr, size_t size, size_t count, FILE *fp);

A description of the parameters :

  • ptr Pointer to a memory block , It can be an array 、 Variable 、 Structure, etc .fread() Medium ptr Used to store the read data ,fwrite() Medium ptr Used to store the data to be written .
  • size: Represents the number of bytes per data block .
  • count: Indicates the number of data blocks to read and write . Theoretically , Every time I read and write size*count Bytes of data .
  • fp: Indicates the file pointer .
  • size_t Is in stddef.h Used in header file typedef Defined data types , Represents an unsigned integer , That is, non negative numbers , It is often used to express quantity .
  • Return value : Returns the number of blocks successfully read and written , That is to say count. If the return value is less than count:
    about fwrite() Come on , There must be a write error , It can be used ferror() Function detection .
    about fread() Come on , May have read to the end of the file , An error may have occurred , It can be used ferror() or feof() testing .

example :

 Enter an array from the keyboard , Write the array to the file and read it out 
#include <stdio.h>
#define N 5
int main(){
    
	//  Put the data entered from the keyboard into a, The data read from the file is put into b
	int a[N], b[N];
	int i, size = sizeof(int);
	FILE *fp;

	if((fp=fopen("d:\\demo.txt", "rb+")) == NULL){
    
		printf("cannot open file, press any key to exit! \n");
		getch();
		exit(1);
	}
	//  Enter data from keyboard , And save it to the array a
	for(i=0; i<N; i++){
    
		scanf("%d", &a[i]);
	}
	//  Will array a Write to file 
	fwrite(a, size, N, fp);
	//  Reposition the position pointer in the file to the beginning of the file 
	rewind(fp);
	//  Read the contents from the file and save them to the array b
	fread(b, size, N, fp);
	//  Display the array on the screen b The content of 
	for(i=0; i<N; i++){
    
		printf("%d ", b[i]);
	}
	printf("\n");
	fclose(fp);
	system("pause");
	return 0;
}
 result :
	23 409 500 100 222
	23 409 500 100 222

 

6、 ... and :C Pointer movement of language files

6.1: introduce

The file reading and writing functions described above are sequential reading and writing , That is, reading and writing files can only start from scratch , Read and write data in sequence . But in the actual development, we often need to read and write the middle part of the file , To solve this problem , You have to move the position pointer inside the file first , Read and write again . This way of reading and writing is called random reading and writing , That is, start reading and writing from anywhere in the file . The key to random reading and writing is to move the position pointer as required , This is called file positioning .

6.2: File location function rewind and fseek

  • rewind() Used to move the position pointer to the beginning of the file :void rewind(FILE *fp);
  • fseek() Used to move the position pointer to any position :int fseek(FILE *fp, long offset, int origin);

Parameter description :

  1. fp For file pointer , That is, the moved file .
  2. offset For offset , That is, the number of bytes to be moved . The reason is long type , I want to move more , Can handle larger files .
  3. origin Is the starting position , That is, where to start calculating the offset .C There are three starting positions of language regulations , At the beginning of the file 、 Current location and end of file , Each position is represented by a corresponding constant :
 The starting point 		 Constant names 				 Constant values 
 Beginning of file 		SEEK_SET				0
 The current position 		SEEK_CUR				1
 end of file 		SEEK_END				2

for example , Move the position pointer to the beginning of the file 100 Bytes :fseek(fp, 100, 0);

原网站

版权声明
本文为[Prison plan progress 50%]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270404363018.html