The ansi c standard is supported by almost all operating systems. The ansi c standard provides complete I/O functions, with these I/O operations, we can control program input and output, Read and Write System Disk Files. This article records the user process I/O buffer introduction, file read/write, file location operations, and so on.
Library functions and system calls
Files are stored on disks. How to control file read/write in a running program (process, we can see how the application controls the general principle of system resources (including files on disks.
The operating system helps us manage hardware resources, encapsulate underlying implementations, and provide interfaces (System Call functions) for upper-layer applications to call. You can directly use the System Call functions provided by the operating system to control the reading and writing of files. However, we generally do not advocate this in applications because of performance problems. When an application calls a system to call a function, the operating system changes from the user State to the kernel state. After the call is completed, the operating system changes from the kernel state to the user State (implemented through soft interruptions in Linux ), frequent system status switching requires overhead, which may cause performance problems for your applications. In addition, there is the portability problem. The interfaces provided by each operating system are different. If the system calls a function directly in an application, the portability of the program will be poor. In the ansi c standard, we provide standard functions (library functions) to call functions in the operating system. library functions are functions that can complete specific functions and are generally released by a certain standard, and form a recognized standard, so the use of library functions can shield external interface differences between operating systems.
Below are the differences between library functions and System Call functions summarized by netizens.
Buffering and non-buffering
For file access operations, you can use a buffer or not to perform operations on buffered files or non-buffered files.
Buffer File Operations: Advanced file operations. For example, in the first figure, the left branch of the user application allocates a buffer for the opened file in the user process space. The ansi c standard is used for file operations. This article discusses exactly this.
Non-buffered File Operations: Low-level file operations, such as the right branch of the user application in the first figure. There is no File Buffer in the user process space. Posix c standard I/O is used for non-buffered file operations.
Note: The buffer mentioned here all refers to the File Buffer in the user process space. Even if it is not a buffer file operation, multi-level buffering is used in the kernel, instead of directly accessing the disk (refer to the memory structure of the operating system ).
File and file stream
Stream is an abstract data structure, which is used by ansi c to efficiently manage opened file information. In actual programming, it is embodied in the struct file structure in stdio. as defined in the header file, the most important mechanism of stream objects is buffer and format conversion. In Linux, three files are opened for each process by default. The corresponding three streams are standard input streams, standard output streams, and standard error streams. In addition, you need to open and close other files you need.
File I/O operations
Read/write objects can be divided into several types of read/write operations by character, row, block, and format.
(1) read/write file streams by character
The following program uses fgetc and fputc to read the content of a specified file to the standard output (Display). You must specify a file
#include<stdio.h>int main(int argc,char *argv[]){ FILE *fp=NULL; char ch; if(argc<=1) { printf("check usage of %s \n",argv[0]); return -1; } if((fp=fopen(argv[1],"r"))==NULL) { printf("can not open %s\n",argv[1]); return -1; } while ((ch=fgetc(fp))!=EOF) fputc(ch,stdout); fclose(fp); return 0;}
Run the program:
(2) read/write file streams by row
The following is a program that uses fgets and fputs to implement the above functions.
# Include <stdio. h> int main (INT argc, char * argv []) {file * fp = NULL; char STR [20]; If (FP = fopen (argv [1], "R") = NULL) // open the file {printf ("can not open! \ N "); Return-1;} fgets (STR, sizeof (STR), FP); // read sizeof (STR) from the Open File) bytes to fputs (STR, stdout) in STR; // output STR to the standard output fclose (FP); // close the file return 0 ;}
(3) read/write by block
The following is a block-based read/write program implemented using fread and fwrite.
# Include <stdio. h> int main (INT argc, char * argv []) {struct student {char name [10]; int number ;}; file * fp = NULL; int I; struct student Boya [2], boyb [2], * PP, * QQ; If (FP = fopen ("aa.txt", "W +") = NULL) // open the file in read/write mode. If the file exists, it is cleared. If the file does not exist, it is created {// failed to open the file printf ("can not open! \ N "); Return-1;} pp = Boya; QQ = boyb; printf (" Please input two students 'name and number: \ n "); for (I = 0; I <2; I ++, pp ++) scanf ("% s \ % d", PP-> name, & PP-> number ); pp = Boya; fwrite (PP, sizeof (struct student), 2, FP); // write the information entered from the keyboard into the file stream FP rewind (FP ); // locate the read/write location to the file header fread (QQ, sizeof (struct student), 2, FP ); // read two structs from the file stream FP to QQ printf ("Name \ t number \ n"); for (I = 0; I <2; I ++, qq ++) // outputs the content printf ("% s \ t % d \ n", QQ-> name, QQ-> Number) in QQ ); fclose (FP); Return 0 ;}
(4) read/write according to formatting
The following program uses sprintf and sscanf for file read/write operations.
# Include <stdio. h> int main () {file * fp = NULL; int I = 20; char CH = 'D'; If (FP = fopen ("F2 ", "R +") = NULL) {printf ("Open File F2 failed. "); Return-1;} fprintf (FP," % d: % C \ n ", I, CH); // write the file int new_ I = 0 in the specified format; char new_ch; rewind (FP); // reset the read/write pointer to fscanf (FP, "% d: % C \ n", & new_ I, & new_ch ); // read the file printf ("new_ I = % d, new_ch = % C \ n", new_ I, new_ch); fclose (FP); Return 0 ;}
Program running result:
Besides, the buffer zone
We can find that no buffer is specified for read/write operations in the above four forms, but they all use the File Buffer located in the user's process space. This is because for any stream, if the buffer type is not specified, the system specifies the default buffer type. If you want to specify a buffer, you can use the setbuf () or setvbuf () function to specify the buffer. The declaration of the two functions is as follows:
Extern void setbuf (Stream object, buffer );
If the buffer is set to null, the buffer is disabled.
Extern int setvbuf (Stream object, buffer, mode, buffer size)
Setvbuf is more flexible than setbuf. The modes can be set to 0, 1, and 2, indicating full buffering, row buffering, and no buffering. If the mode is set to 2, the second and fourth parameters are ignored.
The following is a program for modifying the buffer zone:
/* Example show usage of setbuf() &setvbuf() */#include<stdio.h>#include<error.h>#include<string.h>int main( int argc , char ** argv ){int i;FILE * fp;char msg1[]="hello,wolrd\n";char msg2[] = "hello\nworld";char buf[128];//open a file and set nobuf(used setbuf).and write string to it,check it before close of flush the streamif(( fp = fopen("no_buf1.txt","w")) == NULL){perror("file open failure!");return(-1);}setbuf(fp,NULL);memset(buf,'\0',128);fwrite( msg1 , 7 , 1 , fp );printf("test setbuf(no buf)!check no_buf1.txt\n");printf("now buf data is :buf=%s\n",buf);printf("press enter to continue!\n");getchar();fclose(fp);//open a file and set nobuf(used setvbuf).and write string to it,check it before close of flush the streamif(( fp = fopen("no_buf2.txt","w")) == NULL){perror("file open failure!");return(-1);}setvbuf( fp , NULL, _IONBF , 0 );memset(buf,'\0',128);fwrite( msg1 , 7 , 1 , fp );printf("test setvbuf(no buf)!check no_buf2.txt\n");printf("now buf data is :buf=%s\n",buf);printf("press enter to continue!\n");getchar();fclose(fp);//open a file and set line buf(used setvbuf).and write string(include '\n') to it,////check it before close of flush the streamif(( fp = fopen("l_buf.txt","w")) == NULL){perror("file open failure!");return(-1);}setvbuf( fp , buf , _IOLBF , sizeof(buf) );memset(buf,'\0',128);fwrite( msg2 , sizeof(msg2) , 1 , fp );printf("test setvbuf(line buf)!check l_buf.txt, because line buf ,only data before enter send to file\n");printf("now buf data is :buf=%s\n",buf);printf("press enter to continue!\n");getchar();fclose(fp);//open a file and set full buf(used setvbuf).and write string to it for 20th time (it is large than the buf)//check it before close of flush the streamif(( fp = fopen("f_buf.txt","w")) == NULL){perror("file open failure!");return(-1);}setvbuf( fp , buf , _IOFBF , sizeof(buf) );memset(buf,'\0',128);fwrite( msg2 , sizeof(msg2) , 1 , fp );printf("test setbuf(full buf)!check f_buf.txt\n");printf("now buf data is :buf=%s\n",buf);printf("press enter to continue!\n");getchar();fclose(fp);}
Other File Operations
The following describes some common functions used in file operations.
Open and Close file operations fopen and fclose
Fp = fopen (file name, file operation method );
File operations are as follows:
Close the file using the fclose (File pointer); or the fcloseall () function.
File stream Detection
Extern int feof (Stream object)
It is used to determine whether the stream object has read the end of the file. If it returns 1, otherwise 0 is returned;
Extern int ferror (Stream object)
It is used to determine whether a stream object has an error. If no error exists, 0 is returned. Otherwise, non-0 is returned.
Extern long int ftell (Stream object)
Returns the number of bytes between the current read/write position and the start of the file. If the execution fails,-1 is returned.
Extern int fseek (Stream object, offset distance, reference position)
The reference positions include 0, 1, and 2, indicating the beginning, current location, and end of the file, respectively.
Move the read/write location to the offset from the reference location. If the call succeeds, 0 is returned. Otherwise,-1 is returned.
Extern void rewind (Stream object)
Reset the read/write location to the beginning of the file.
C file IO