C language File read-write operation summary __c language

Source: Internet
Author: User
Tags fread modifiers rewind
C language File read and write operation summary

C Language File operation

I. Reading and writing of standard documents

1. Open the file

The open operation of the fopen () file means that the file specified by the user is allocated a filename in memory and the pointer to the structure is returned to the user program, which can then be used by the user program to enable access to the specified file. When you use the Open function, you must give the file name, how the file is manipulated (read, write, or read/write), and if the file name does not exist, it means to establish (errors are made only for the write file, for the read file) and point the file pointer to the file. If a file with the same name already exists, the file is deleted, and if there is no file with the same name, the file is established and the file pointer points to the beginning of the file.

fopen (char *filename,char *type);

where *filename is the filename pointer to open the file, typically in double quotes, or a path name separated by a double backslash. The *type parameter indicates how the file is opened. It can be used in the following ways: the way meaning "R" open, read-only; "W" Open, the file pointer refers to the end, writes only, "a" opens, points to the tail of the file, appends to the existing file, "RB" opens a binary file, reads only, "WB" opens a binary file, writes only; "AB" opens a binary file, append; "r+" to open an existing file in read/write mode; w+ "Create a new text file in read/write mode;" A + "opens a file file for append read/write;" rb+ "opens a binary file in read/write mode;" wb+ "to read/ Write method to create a new binary file; "ab+" opens a binary file as read/write to append; When a file is successfully opened with fopen (), the function returns a filename that returns a null pointer if the file fails to open. To open the test file, write:

FILE *FP; if ((Fp=fopen ("Test", "W") ==null) {printf ("File cannot be opened/n"), exit (), or else printf ("file opened for writing/n"); ... fclose (FP);

The DOS operating system has a limited number of simultaneous files, with a default value of 5, which can be changed by modifying the Config.sys file.

2. Close the file function fclose ()

When the file operation is complete, it must be closed with the fclose () function, because when the open file is written, the contents of the file buffer are not written to the open file and are lost if the space is not written. The content that stays in the file buffer can be written to the file only when the open file is closed, making the file complete. Furthermore, once the file is closed, the file structure corresponding to it is freed, which protects the closed file because the access to the file is not performed. The shutdown of the file also means that the file's buffer is freed.

int fclose (FILE *stream);

It means that the function closes the file corresponding to the files pointer and returns an integer value. If the file is successfully closed, a value of 0 is returned, otherwise a value other than 0 is returned. The following methods are commonly used for testing:

if (fclose (FP)!=0) {printf ("File cannot be closed/n"), exit (1), Else printf ("File is now closed/n");

When you open more than one file and then close it at the same time, you can use the Fcloseall () function, which closes all files that are open in your program. int Fcloseall (); The function closes all open files, writes the contents of each file buffer to the appropriate file, releases the buffers, and returns the number of closed files. If 4 files are closed, then execute: N=fcloseall (); , n should be 4.

3. Reading and writing of documents

(1). A function to read and write characters in a file (read only one character in a file at a time):

int fgetc (FILE *stream);

int GetChar (void);

int FPUTC (int ch,file *stream);

int putchar (int ch);

int getc (FILE *stream);

int putc (int ch,file *stream);

where the FGETC () function reads one character from the file pointed to by the stream pointer, for example: CH=FGETC (FP); Reads a character from the file that points to the stream pointer fp. and to CH, when the fgetc () function is executed, if the file pointer is at the end of the file, it encounters the file end flag EOF (whose corresponding value is-1), and the function returns a-1 to CH, It is often used in a program to check whether the function return value is-to determine whether it has been read to the end of the file, and to decide whether to continue.

#include "stdio.h" #include <stdlib.h> int main () {FILE *FP char ch; if (Fp=fopen ("MyFile.txt", "R") ==null) {Prin TF ("File cannot be opened/n"); Exit (1); while ((CH=FGETC (FP))!=eof) FPUTC (ch,stdout); Fclose (FP); }

The program opens the MyFile.txt file as read-only, and when the while loop executes, the file pointer moves one character position at a time after each loop. Read the character specified by the file pointer to the CH variable with the fgetc () function, then display it on the screen with the FPUTC () function, and close the file when you read the end of file flag EOF. The above program uses the FPUTC () function, which writes the value of the character variable ch to the file specified by the stream pointer, and the read characters are displayed on the monitor because the stream pointer is using the standard output (display) file pointer stdout. Another example: FPUTC (CH,FP); The function executes the structure, sending the characters represented by CH to the file pointed to by the stream pointer FP. In TC, PUTC () is equivalent to FPUTC () and getc () is equivalent to Fgetc (). Putchar (c) is equivalent to FPUTC (c,stdout) and GetChar () is equivalent to Fgetc (stdin). Note that it is unscientific to use char ch here, because at the end of the final judgment it is to look at the ch!=eof, and the EOF value is-1, which is obviously not comparable to char. So, some use, we are all defined as int ch.

(2). Functions to read and write strings in a file

Char *fgets (char *string,int n,file *stream);

Char *gets (char *s);

int fprintf (FILE *stream,char *format,variable-list);

int fputs (char *string,file *stream);

int fscanf (FILE *stream,char *format,variable-list);

where the fgets () function n-1 a character in the file specified by the stream pointer, and reads to the array of characters pointed to by the pointer string, for example: Fgets (BUFFER,9,FP); The 8 characters in the file that the FP points to are read into the buffer memory area, which can be either a defined character array or a dynamically allocated memory area. Note that the fgets () function reads ' n ' to stop, regardless of whether a number is met or not. Plus '/0 ' at the end of the read string. After the fgets () function finishes executing, a pointer to the string is returned. If you read the end of a file or make an error, returns a null pointer, the feof () function is used to determine whether the end of the file or the Ferror () function to test for errors, for example, the following program reads the first line in the Test.txt file with the fgets () function and displays it:

#include "stdio.h" int main () {FILE *fp; char str[128]; if (Fp=fopen ("Test.txt", "R") ==null) {printf ("Cannot open file/n "); Exit (1); while (!feof (FP)) {if (fgets (STR,128,FP)!=null) printf ("%s", str);} fclose (FP); }

When the gets () function executes, it is read as long as no line break or end of file sign is encountered. So when you read it, you need the user to control it, or it can cause a storage overflow. The fputs () function specifies that the file be written to a string pointed to by string, '/0 ' is not written to the file. fprintf () and fscanf () are similar to the printf () and scanf () functions, unlike the printf () function, which is to display output, fprintf () is the output of the file to which the stream pointer is directed, and FSCANF () is entered from the file. The following procedure is to enter some characters into the file Test.dat:

#include <stdio.h> #include <stdlib.h> int main () {char *s= "That's good news"; int i=617; FILE *FP; Fp=fopen ("Test.dat", "w"); /* Create a text file to write only/fputs ("Your score of TOEFL is", FP); /* Write a string of characters to the file/* FPUTC (': ', FP); /* Write a colon to the file: * * fprintf (FP, "%d/n", I); * * Write an integer to the file/fprintf (FP, "%s", s); /* Write a string to the file/fclose (FP); }

The DOS type command displays the contents of the TEST.DAT as follows: The screen shows Your score of TOEFL is:617 that ' s good news the following procedure is to display the contents of the above file Test.dat on the screen:

#include <stdio.h> int main () {char s[24], m[20]; int i; FILE *FP; Fp=fopen ("Test.dat", "R"); /* Open Text file read Only/fgets (S, FP); /* Reads 23 characters from the File/printf ("%s", s); FSCANF (FP, "%d", &i); /* Read integer number/printf ("%d", I); Putchar (FGETC (FP)); /* Read a character at the same time output */fgets (M,, FP); /* Read 16 characters/* puts (m); * * Output Read string/fclose (FP); }

After running screen display: Your score of TOEFL is:617 that ' s good news

4. Purge and set file buffers

(1). Purge File Buffer function:

int fflush (FILE *stream);

int Flushall ();

The Fflush () function clears the contents of the file buffer that is pointed to by the stream, which is used to clear the buffer immediately after some data has been written, so as to avoid damaging the original data when the operation is incorrect. Flushall () Clears the file buffers for all open files.

(2). set File buffer function

void Setbuf (FILE *stream,char *buf);

void Setvbuf (FILE *stream,char *buf,int type,unsigned size);

These two functions will allow the user to create their own file buffers after the file is opened instead of using the fopen () function to open the default buffer for the file. For the Setbuf () function, the buffer length indicated by BUF is determined by the value of the macro bufsize defined in the file stdio.h, with a default value of 512 bytes. When the selected buf is empty, the SETBUF function will make file I/O with no buffering. For the SETVBUF function, the buffer is allocated by the malloc function. The parameter size indicates the length of the buffer (must be greater than 0). The parameter type, in turn, represents a buffered type whose value can be as follows: The value of type value _IOFBF the file full buffer, that is, the buffer is filled to read and write to the file _iolbf file line buffer, that is, when the buffer received a newline character, In order to read and write files _IONBF file does not buffer, at this time ignoring the value of buf,size, directly read and write files, no longer through the file buffer buffer.

5. Random Read and write function of file

The character/string reads and writes of the files described earlier are all read and write in sequential files, that is, read and write always from the beginning of the file. This clearly does not meet our requirements, the C language provides a mobile file pointer and random read and write functions, they are:

(1). Move the file pointer function:

Long Ftell (FILE *stream);

int Rewind (FILE *stream);

Fseek (FILE *stream,long offset,int origin);

The function Ftell () is used to get the offset of the file pointer from the beginning of the file. An error is indicated when the return value is-1. The rewind () function is used to move the file pointer to the beginning of the file, return 0 when the move succeeds, or return a value other than 0. The fseek () function is used to move an offset byte origin the file pointer, where Origin points to the following:

Origin numeric representation of the exact location

Seek_set 0 File Start

Seek_cur 1 file pointer current position

Seek_end 2 End of file

For example: Fseek (fp,10l,0); Move the file pointer from the beginning of the file to the 10th byte, because the offset parameter requires a long integer, so it takes l after the number.

Fseek (fp,-15l,2); Move the file pointer 15 bytes forward from the end of the file.

(2). File random Read and write function

int fread (void *ptr,int size,int nitems,file *stream);

int fwrite (void *ptr,int size,int nitems,file *stream);

The Fread () function reads Nitems data items from the file specified by the stream pointer, each data item has a length of size byte, the read Nitems data item is stored in the memory buffer pointed to by the PTR pointer, and the file pointer moves backwards with the number of bytes read when the Fread () function is executed. , the last move end is equal to the number of bytes actually read out. When the function finishes, it returns the number of data items that are actually read, not necessarily equal to the set's Nitems, because if there are not enough data items in the file or errors in the middle of the reading, the number of entries returned is less than the set Nitems. When the number of returns is not equal to nitems, it can be checked with the feof () or ferror () function. The fwrite () function extracts the Nitems data item of length size byte from the buffer pointed to by the PTR, writes to the file pointed to by the stream pointer stream, and after that operation, the file pointer moves backwards, and the number of bytes moved is equal to the number of bytes written to the file. When the function completes, the number of data entries written will also be returned.

Ii. Reading and writing of non-standard documents

This type of function was first used for UNIX operating systems, the ANSI standard is undefined, but it is sometimes used, and the DOS 3.0 version supports these functions. Their header file is io.h. Since we don't use these functions very often, here's a simple word.

1. Opening and closing of files

The open () function opens the file in a format that is called int open (char *filename, int access); This function indicates that the file named filename is opened as required by access, and the return value is a file descriptor, where access has two parts: basic mode and modifiers, both of which are connected in the form of "(or"). Modifiers can have multiple, but only one of the basic patterns. Access's provisions--------------------------------------------------------the meaning of the basic schema meaning modifier---------------------------------- ----------------------O_rdonly Read-only o_append file pointer points to the end o_wronly write-only o_creat file does not exist, the property is based on the basic mode attribute O_rdwr read and write O_trunc if the file exists, it The length is 0, the property is unchanged o_binary opens a binary file O_text opens a text file---------------------------------------------------------open () function opens successfully , the return value is the value of the file descriptor (non-negative), otherwise 1 is returned. The close () function closes the file opened by the open () function, which is invoked in the form of an int-close (int handle); This function closes the file description Word handle the attached file.

2. Read-write function

int read (int handle, void *buf, int count);

The read () function reads the count bytes into the buffer referred to in BUF from the handle (file descriptor) file, the return value is the actual number of bytes read, and return 1 indicates an error. A return of 0 indicates the end of the file. The call format for the write () function is: int write (int handle, void *buf, int count); The write () function writes count bytes from the buffer pointed to by the BUF to the handle-connected file, and the return value is the number of bytes actually written.

3. Random location function

The call format for the Lseek () function is: int lseek (int handle, long offset, int fromwhere);

This function locates the file position pointer attached to the handle, with the same functionality and usage as the fseek () function. The call format for the tell () function is: long tell (int handle); This function returns the current location pointer of the file attached to the handle, with the same functionality and usage as Ftell ()

5. read function and write function

Source: Ant-C + + standard programming Author: Antigloss

1. Read

#include ssize_t read (int filedes, void *buf, size_t nbytes); Return value: Number of bytes read; 0 (read to EOF);-1 (Error) the Read function reads Nbytes bytes into BUF from the open file specified by Filedes. The following conditions cause the number of bytes read to be less than nbytes:

A. When reading a normal file, it is not enough nbytes bytes to read the end of the file. For example, if the file is only 30 bytes, and we want to read 100 bytes, we actually read only 30 bytes, and the Read function returns 30. Using the Read function to effect this file at this time will cause read to return 0.

B. When reading from terminal equipment (terminal device), you can normally read only one row at a time.

C. When reading from the network, the network cache may cause the number of bytes read to be less than nbytes bytes.

D. When reading pipe or FIFO, the number of bytes in pipe or FIFO may be less than nbytes.

E. When reading from a record-oriented-oriented device, certain recording-oriented devices, such as tapes, can return up to one record at a time. F. Interrupted by a signal while reading part of the data. The read operation begins with the CFO. Before successful return, the CFO increases the number of bytes actually read.

2. Write

#include ssize_t write (int filedes, const void *buf, size_t nbytes); Return value: Number of bytes written to file (successful);-1 (Error) The Write function writes nbytes byte data to the Filedes with the data source buf. The return value is always equal to nbytes, otherwise it is an error. A common cause of error is that disk space is full or the file size limit is exceeded. For ordinary files, the write operation begins with the CFO. If O_append is used when the file is opened, the data is written to the end of the file for each write operation. After successful writing, the CFO increases the number of bytes actually written.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.