C language file operation functions
Fopen (open FILE) related function open, fclose header FILE # include definition function FILE * fopen (const char * path, const char * mode ); function Description: the path string contains the path and file name of the file to be opened. The mode string represents the stream format. Mode has the following types of strings: r. To open a read-only file, the file must exist. R + open a readable file, which must exist. W. Open and write only the file. If the file exists, the file length is 0, indicating that the file content will disappear. If the file does not exist, the file is created. W + open the readable and writable file. If the file exists, the file length is cleared to zero, that is, the file content disappears. If the file does not exist, the file is created. A. Open and write-only files as an attachment. If the file does not exist, the file will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be retained. A + opens readable and writable files by appending them. If the file does not exist, the file will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be retained. Copy the Code as follows:
r Open text file for reading. The stream is positioned at the beginning of the file.r+ Open for reading and writing. The stream is positioned at the beginning of the file.w Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.w+ Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is posi‐tioned at the beginning of the file.a Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at theend of the file.a+ Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file posi‐tion for reading is at the beginning of the file, but output is always appended to the end of the file.
The preceding morphological string can be added with a B character, such as a combination of rb, w + B, and AB +. The B character is added to indicate that the file opened by the function library is a binary file, rather than text files. However, this character is ignored in the POSIX System in Linux. The new file created by fopen () has the S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH (0666) Permission. For the File Permission, see umask value. When the returned value file is successfully opened, the file pointer pointing to the stream will be returned. If the file fails to be opened, NULL is returned and the error code is stored in errno. Note: After opening a file, the file will be read or written. If opening the file fails, the subsequent read/write operations will not be smooth. Therefore, in the fopen () then, make error judgment and handling. Sample copy code:
#includemain(){FILE * fp;fp=fopen(“noexist”,”a+”);if(fp= =NULL) return;fclose(fp);}
1. fprintf function: Transfer formatted output to a FILE header FILE: # include function prototype: int fprintf (FILE * stream, char * format [, argument,...]); FILE * a FILE-type pointer char * formats the input function, and returns the same value as the format in printf: the number of bytes converted upon success, A negative fp = fopen ("/local/test. c "," a + "); fprintf (fp," % s \ n ", str); 2. fscanf function: format the input header FILE from a stream: # include function prototype: int fscanf (FILE * stream, char * format [, argument...]); FILE * a FILE-type pointer char * formats the output function, and returns the same value as the format in scanf: the number of bytes converted upon success, return a negative fp = fopen ("/l Ocal/test. c "," a + "); fscanf (fp," % s ", str); 3. clearerr (error flag for clearing FILE streams) function feof header FILE # include definition function void clearerr (FILE * stream); Function Description clearerr () clears the error flag used by the file stream specified by the stream parameter. Return Value 4. fclose (close FILE) related functions close, fflush, fopen, setbuf header FILE # include definition function int fclose (FILE * stream); Function Description fclose () is used to close the previous fopen () open file. This action writes data in the buffer zone to a file and releases the file resources provided by the system. If the object is successfully closed, 0 is returned. If an error occurs, EOF is returned and the error code is saved to errno. The error code EBADF indicates that the parameter stream is not an open file. For more information, see fopen (). 5. fdopen (convert FILE description to FILE pointer) related functions fopen, open, fclose header FILE # include definition function FILE * fdopen (int fildes, const char * mode ); function Description fdopen () converts the file description of fildes to the corresponding file pointer and returns the result. The mode string represents the stream format of the file pointer, which must be the same as the read/write mode of the original file description. For more information about the mode string format, see fopen (). If the return value is converted successfully, the file pointer pointing to the stream is returned. If the Error Code fails, NULL is returned, and the error code is stored in errno. Sample copy code: # includemain () {FILE * fp = fdopen (0, "w +"); fprintf (fp, "% s/n", "hello! "); Fclose (fp) ;}execute hello! 6. feof (check whether the FILE stream has read the end Of the FILE) related functions fopen, fgetc, fgets, fread header FILE # include definition function int feof (FILE * stream); Function Description feof () it is used to detect whether the end of the file is read, and the ending number stream is the object pointer returned by fopen. If the end of the file is reached, a non-zero value is returned. Otherwise, 0 is returned. The return value is a non-zero value, indicating that the object has reached the end of the object. 7. fflush (update buffer) related functions write, fopen, fclose, setbuf header FILE # include definition function int fflush (FILE * stream); Function Description fflush () the data in the buffer is forcibly written back to the file specified by the parameter stream. If the parameter stream is NULL, fflush () updates all open file data. If the return value is successful, 0 is returned. If the return value is failed, EOF is returned. The error code is stored in errno. The file specified by the error code "stream" is not opened, or the file is in read-only status. For other error codes, see write (). 8. fgetc (one character read from the FILE) related functions open, fread, fscanf, getc header FILE include definition function nt fgetc (FILE * stream); Function Description fgetc () read a character from the file indicated by the parameter stream. If you read the end Of the file without data, the EOF is returned. If the returned value is getc (), the read characters are returned. If the returned value is EOF, the returned values are at the end of the file. Sample copy code:
#includemain(){FILE *fp;int c;fp=fopen(“exist”,”r”);while((c=fgetc(fp))!=EOF)printf(“%c”,c);fclose(fp);}
9. fgets (read a string from the FILE) related functions open, fread, fscanf, getc header FILE include definition function har * fgets (char * s, int size, FILE * stream ); function Description: fgets () is used to read characters from the file referred to by the parameter stream to the memory space referred to by the parameter s, until a line break occurs, the end of the file is read, or the size-1 character is read, NULL is added as the string. If gets () is returned successfully, the s pointer is returned. If NULL is returned, an error occurs. Sample copy code: # includemain () {char s [80]; fputs (fgets (s, 80, stdin), stdout );} run this is a test/* input */this is a test/* output */10. fileno (the FILE description term used to return the FILE stream) function open, fopen header FILE # include definition function int fileno (FILE * stream); Function Description fileno () used to obtain the file description used by the file stream specified by the parameter stream. The Return Value Returns the description of the file. Sample copy code:
# Includemain () {FILE * fp; int fd; fp = fopen ("/etc/passwd", "r"); fd = fileno (fp ); printf ("fd = % d/n", fd); fclose (fp);} execute fd = 3
12. fputc (write a specified character to a FILE stream) related functions fopen, fwrite, fscanf, putc header FILE # include definition function int fputc (int c, FILE * stream ); function Description: fputc converts parameter c to unsigned char and writes it to the file specified by the parameter stream. If the returned value is fputc (), a successfully written character is returned, that is, the parameter c. If EOF is returned, the write operation fails. Sample copy code: # includemain () {FILE * fp; char a [26] = "abcdefghijklmnopqrstuvwxyz"; int I; fp = fopen ("noexist ", "w"); for (I = 0; I <26; I ++) fputc (a, fp); fclose (fp);} 13. fputs (write a specified string into a file) related functions fopen, fwrite, fscanf, fputc, putc header file # include definition function int fputs (const char * s, FILE * stream); Function Description fputs () is used to write the string referred to by parameter s to the FILE referred to by parameter stream. If the return value is successful, the number of written characters is returned. If the return value is EOF, an error occurs. For an example, see fgets (). Fread (reads data from a file stream) related functions fopen, fwrite, fseek, fscanf header file # include definition function size_t fread (void * ptr, size_t size, size_t nmemb, FILE * stream); Function Description fread () is used to read data from the FILE stream. The stream parameter is an opened file pointer. the ptr parameter points to the data space to be read. The number of characters read is determined by the size * nmemb parameter. Fread () returns the number of nmemb actually read. If this value is smaller than the nmemb parameter, it indicates that the file may be read at the end or an error occurs. In this case, feof () must be used () or ferror () to determine what happens. The Return Value Returns the number of nmemb actually read. The sample copy code is as follows:
# Include # define nmemb 3 struct test {char name [20]; int size;} s [nmemb]; int main () {FILE * stream; int I; stream = fopen ("/tmp/fwrite", "r"); fread (s, sizeof (struct test), nmemb, stream); fclose (stream ); for (I = 0; I printf ("name [% d] = %-20 s: size [% d] = % d/n", I, s. name, I, s. size);} Run name [0] = Linux! Size [0] = 6 name [1] = FreeBSD! Size [1] = 8 name [2] = Windows2000 size [2] = 11
14. freopen (Open FILE) related functions fopen, fclose header FILE # include definition function FILE * freopen (const char * path, const char * mode, FILE * stream ); function Description: the path string contains the path and file name of the file to be opened. For details about the mode parameter, see fopen. The stream parameter is an opened file pointer. Freopen () will close the file stream opened by the original stream, and then open the file with the path parameter. When the returned value file is successfully opened, the file pointer pointing to the stream will be returned. If the file fails to be opened, NULL is returned and the error code is stored in errno. Sample copy code: # includemain () {FILE * fp; fp = fopen ("/etc/passwd", "r "); fp = freopen ("/etc/group", "r", fp); fclose (fp);} 15. fseek (read/write location of a mobile FILE stream) related functions rewind, ftell, fgetpos, fsetpos, lseek header FILE # include definition function int fseek (FILE * stream, long offset, int whence ); function Description: fseek () is used to move the read/write location of a file stream. The stream parameter is an opened file pointer, And the offset parameter is the number of read/write locations to be moved Based on the whence parameter. The whence parameter is one of the following: the offset displacement from the beginning of the SEEK_SET file is a new read/write location. SEEK_CUR increases the offset displacement at the current read/write position. SEEK_END points the read/write position to the end of the file and then increases the offset displacement. When the whence value is SEEK_CUR or SEEK_END, the offset parameter allows negative values. The following are special usage methods: 1) To move a read/write location to the beginning of a FILE: fseek (FILE * stream, 0, SEEK_SET); 2) to move the read/write location to the end of the FILE: fseek (FILE * stream, 0, 0SEEK_END); Return Value: 0 if the call is successful; if an error exists,-1 is returned, errno stores error codes. Note that fseek () does not return the read/write location like lseek (). Therefore, ftell () must be used to obtain the current read/write location. Sample copy code:
# Includemain () {FILE * stream; long offset; fpos_t pos; stream = fopen ("/etc/passwd", "r"); fseek (stream, 5, SEEK_SET ); printf ("offset = % d/n", ftell (stream); rewind (stream); fgetpos (stream, & pos ); printf ("offset = % d/n", pos); pos = 10; fsetpos (stream, & pos); printf ("offset = % d/n ", ftell (stream); fclose (stream);} execute offset = 5 offset = 0 offset = 10
16. ftell (get the reading location of the FILE stream) related functions fseek, rewind, fgetpos, fsetpos header FILE # include definition function long ftell (FILE * stream); Function Description ftell () used to obtain the current read/write location of a file stream. The stream parameter is an opened file pointer. Return Value: if the call is successful, the current read/write location is returned. If an error occurs,-1 is returned, and errno stores the error code. Error code: file stream with invalid parameter stream or removable read/write location. For an example, see fseek (). 17. fwrite (write data to a file stream) related functions fopen, fread, fseek, fscanf header file # include definition function size_t fwrite (const void * ptr, size_t size, size_t nmemb, FILE * stream); Function Description fwrite () is used to write data into the FILE stream. The stream parameter is an opened file pointer. the ptr parameter points to the data address to be written. The total number of characters written is determined by the parameter size * nmemb. Fwrite () returns the number of nmemb actually written. The Return Value Returns the number of nmemb actually written. Sample copy code:
# Include # define set_s (x, y) {strcoy (s [x]. name, y); s [x]. size = strlen (y) ;}# define nmemb 3 struct test {char name [20]; int size ;}s [nmemb]; main () {FILE * stream; set_s (0, "Linux! "); Set_s (1, "FreeBSD !"); Set_s (2, "Windows2000."); stream = fopen ("/tmp/fwrite", "w"); fwrite (s, sizeof (struct test), nmemb, stream ); fclose (stream);} For more information, see fread ().
18. getc (read a character from the FILE) related functions read, fopen, fread, fgetc header FILE # include definition function int getc (FILE * stream); Function Description getc () it is used to read a character from the file referred to by the parameter stream. If you read the end Of the file without data, the EOF is returned. Although getc () and fgetc () act the same way, getc () is defined as a macro and is not a real function call. If the returned value is getc (), the read characters are returned. If the returned value is EOF, the returned values are at the end of the file. For an example, see fgetc (). 19. getchar (reads one character from the standard input device) related functions: fopen, fread, fscanf, getc header file # include definition function int getchar (void); Function Description getchar () it is used to read a character from the standard input device. Convert the character from unsigned char to int and return the result. If the returned value is getchar (), the read characters are returned. If the returned value is EOF, an error occurs. Additional descriptions getchar () is not a real function, but is defined by the getc (stdin) Macro. Sample copy code: # includemain () {FILE * fp; int c, I; for (I = 0li <5; I ++) {c = getchar (); putchar (c) ;}} run 1234/* input */1234/* output */20. gets (reads a string from the standard input device) related functions: fopen, fread, fscanf, fgets header file # include definition function: char * gets (char * s); Function Description: gets () it is used to read characters from the standard device to the memory space specified by parameter s until a line break occurs or the end of the file is read. Then, NULL is added as the string. If gets () is returned successfully, the s pointer is returned. If NULL is returned, an error occurs. Note: Because gets () cannot know the size of string s, it is easy to cause a buffer overflow security problem because it must end the input only when a newline character or the end of the file is encountered. We recommend that you use fgets () instead. For more information, see fgets () 21. mktemp (generate a unique temporary file name) function tmpfile header file # include definition function char * mktemp (char * template); Function Description mktemp () is used to generate a unique temporary file name. The last six characters in the file name string referred to by the template parameter must be XXXXXX. The generated file name is returned by a string pointer. When the returned value file is successfully opened, the file pointer pointing to the stream will be returned. If the file fails to be opened, NULL is returned and the error code is stored in errno. Additional instructions: the file name string referred to by the template parameter must be declared as an array, for example, char template [] = "template-XXXXXX"; char * template = "template-XXXXXX" cannot be used "; sample copy code: # includemain () {char template [] = "template-XXXXXX"; mktemp (template); printf ("template = % s/n ", template);} 22. putc (write a specified character to a FILE) related functions fopen, fwrite, fscanf, fputc header FILE # include definition function int putc (int c, FILE * stream ); function Description putc () converts parameter c to unsigned char and writes it to the file specified by the parameter stream. Although putc () works the same as fputc (), putc () is defined as a macro and is not a real function call. The return value putc () will return the successfully written character, that is, the parameter c. If EOF is returned, the write operation fails. For an example, see fputc (). 23. putchar (writing specified characters to the standard output device) related functions: fopen, fwrite, fscanf, fputc header file # include definition function int putchar (int c); Function Description: putchar () it is used to write the c character of the parameter to the standard output device. If putchar () is returned, the output is successful, that is, the parameter c. If EOF is returned, the output fails. Additional descriptions putchar () is not a real function, but is defined by the putc (c, stdout) Macro. For more information, see getchar (). 24. rewind (resetting the FILE stream's read/write position to start with the FILE) related functions fseek, ftell, fgetpos, fsetpos header FILE # include definition function void rewind (FILE * stream ); function Description: rewind () is used to move the read/write location of the file stream to the beginning of the file. The stream parameter is an opened file pointer. This function is equivalent to calling fseek (stream, 0, SEEK_SET ). For the return value example, see fseek () 25. setbuf (set FILE stream buffer) related functions setbuffer, setlinebuf, setvbuf header FILE # include definition function void setbuf (FILE * stream, char * buf ); function Description: After opening the file stream and reading the content, call setbuf () to set the buffer zone of the file stream. The parameter stream is the specified file stream, and the parameter buf points to the starting address of the custom buffer. If the buf parameter is a NULL pointer, no buffer IO is required. Setbuf () is equivalent to calling: setvbuf (stream, buf, buf? _ IOFBF: _ IONBF, BUFSIZ) Return Value 26. setbuffer (set FILE stream buffer) related functions setlinebuf, setbuf, setvbuf header FILE # include definition function void setbuffer (FILE * stream, char * buf, size_t size ); function Description: After opening the file stream and reading the content, call setbuffer () to set the buffer zone of the file stream. The parameter stream is the specified file stream. The parameter buf points to the starting address of the custom buffer. The parameter size is the buffer size. Return Value 27. setlinebuf (set FILE stream as linear buffer) related functions setbuffer, setbuf, setvbuf header FILE # include definition function void setlinebuf (FILE * stream); Function Description setlinebuf () this parameter is used to set the no-buffer IO for file streams. Call: setvbuf (stream, (char *) NULL, _ IOLBF, 0); see setvbuf (). Return Value 28. setvbuf (set FILE stream buffer) related functions setbuffer, setlinebuf, setbuf header FILE # include definition function int setvbuf (FILE * stream, char * buf, int mode, size_t size ); function Description: After opening the file stream and reading the content, call setvbuf () to set the buffer zone of the file stream. The parameter stream is the specified file stream. The parameter buf points to the starting address of the custom buffer. The parameter size is the buffer size, the mode parameter has the following types: _ IONBF, no buffer IO_IOFBF, and no buffer IO. If the buf parameter is a NULL pointer, no buffer IO is required. Return Value 29. ungetc (write the specified character back to the FILE stream) related functions fputc, getchar, getc header FILE # include definition function int ungetc (int c, FILE * stream); Function Description ungetc () write the parameter c back to the file stream specified by the parameter stream. This write-back character is obtained by the next function that reads the file stream. If the return value is successful, a c character is returned. If an error occurs, an EOF is returned. Copy the Code as follows:
# Include int main () {FILE * fp = NULL; char * str; char re; int num = 10; str = (char *) malloc (100 ); // snprintf (str, 10, "test: % s", "0123456789012345678"); // printf ("str = % s \ n", str ); fp = fopen ("/local/test. c "," a + "); if (fp = NULL) {printf (" Fail to open file \ n ");} // fseek (fp,-1, SEEK_END); num = ftell (fp); printf ("test file long: % d \ n", num); fscanf (fp, "% s", str ); printf ("str = % s \ n", str); printf ("test a: % s \ n" , Str); while (re = getc (fp ))! = EOF) {// getc can be used as fgetc printf ("% c", re);} // fread (str, 10, 10, fp); fgets (str, 100, fp); printf ("test a: % s \ n", str); sprintf (str, "xiewei test is: % s", "ABCDEFGHIGKMNI "); printf ("str2 = % s \ n", str); // fprintf (fp, "% s \ n", str); fwrite (str, 2, 10, fp ); num = ftell (fp); if (str! = NULL) {free (str) ;}fclose (fp); return 0 ;}