A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service
C Language File operations
I. Reading and writing of standard documents
1. Opening of the file
The open operation of the fopen () file indicates that the user-specified file will be allocated in memory with a single file structure and a pointer to the structure will be returned to the user program, which will be used by the user program to access the specified file. When using the Open function, you must give the filename, file operation (read, write, or read/write), if the file name does not exist, it means to establish (only for the write file, the read file error), and the file pointer to the beginning of the file. If there is already a file with the same name, delete the file, and if there is no file with the same name, create the file and point the file pointer to the beginning of the file.
fopen (char *filename,char *type);
Where *filename is the file name pointer that you want to open, typically enclosed in double quotation marks, or you can use a double backslash to separate the path name. The *type parameter, however, indicates how the file is opened. It can be used in the following ways: the means "R" is opened, read only; "W" opens, the file pointer refers to the head, only write; "A" opens, pointing to the end of the file, appended to the existing file; "RB" opens a binary file, read only; "WB" opens a binary file, write only; "AB" opens a binary "R+" to open an existing file in read/write mode; "w+" creates a new text file in read/write mode; "A +" opens a file file for append read/write; "rb+" opens a binary file as read/write; "wb+" to read/ Write to create a new binary file; "ab+" opens a binary file in read/write mode to append; When a file is opened successfully with fopen (), the function returns the file pointer, and a null pointer is returned if it fails to open. To open the test file, write:[CPP]View Plaincopy
The DOS operating system has a limit on the number of simultaneous files opened, and the default value is 5, which can be changed by modifying the Config.sys file.
2. Close file function fclose ()
After the file operation is complete, it must be closed with the fclose () function, because when writing to an open file, the contents of the file buffer are not written to the open file if the space is not filled. The contents of the file buffer can only be written to the file when the open file is closed, thus making the file complete. Furthermore, once the file is closed, the file structure corresponding to it is freed, so that the closed file is protected because the access to the file will not be performed. Closing the file also means releasing the buffer for the file.
int fclose (FILE *stream);
It indicates that the function closes the file corresponding to the files pointer and returns an integer value. If the file is closed successfully, a value of 0 is returned, otherwise a non-0 value is returned. The following methods are commonly used for testing:[CPP]View Plaincopy
3. File reading and writing
(1). Functions that read and write characters in a file (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 a character from the file pointed to by the flow pointer, for example: CH=FGETC (FP); A character in the file that the stream pointer FP points to is read out and assigned to CH, and when the fgetc () function is executed, if the file pointer is at the end of the file, then the file end sign EOF (which corresponds to-1) is returned, the function returns a-1 to CH, It is common in the program to check whether the return value of the function is-to determine if the end of the file has been read, and to decide whether to continue.[CPP]View Plaincopy
The program opens the MyFile.txt file as read-only, and when the while loop is executed, the file pointer moves back one character position at a time per loop. Use the fgetc () function to read the character specified by the file pointer into the CH variable and then display it on the screen with the FPUTC () function, closing the file when it reads the end-of-file sign EOF. The above program uses the FPUTC () function, which writes the value of the character variable ch to the file specified by the flow pointer, since the stream pointer is stdout with a standard output (monitor) file pointer, so the characters read will be displayed on the display. Another example: FPUTC (CH,FP); The function executes the structure and sends the characters of CH to the file that the stream pointer fp points to. In TC, PUTC () is equivalent to FPUTC () and getc () is equivalent to Fgetc (). Putchar (c) is equivalent to FPUTC (c,stdout); GetChar () is equivalent to Fgetc (stdin). Note that the use of char ch here is actually unscientific, because when the final Judgment end flag is ch!=eof, the value of EOF is-1, which is obviously not comparable to char. So, for some use, we are all defined as int ch.
(2). Functions for reading and writing strings in Files
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 will n-1 characters from the file specified by the flow pointer, read into the character array 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 thefgets () function reads '/n ' to stop, regardless of whether the number is met or not. At the same time, add '/0 ' at the end of the read string. When the fgets () function finishes executing, it returns a pointer to the string. If the end of the file is read or an error occurs, all returns a null pointer null, so long use the feof () function to determine whether the end of the file or the Ferror () function to test for errors, such as the following program with the Fgets () function read the first line in the Test.txt file and display it:[CPP]View Plaincopy
When the Get () function executes, it continues to be read as long as no line break or end-of-file sign is encountered. Therefore, when it is read, the user is required to control it, otherwise it may cause overflow of the storage area. The fputs () function wants to specify that a file is written to a string that is pointed to by string, and that'/0 ' does not write to the file. fprintf () and fscanf () are similar to the printf () and scanf () functions, the difference is that the printf () function wants the display output, fprintf () is the file output to the flow pointer, and FSCANF () is input from the file. The following procedure is to enter some characters into the file Test.dat:[CPP]View Plaincopy
The DOS type command displays the contents of the TEST.DAT as follows: Screen display Your score of the TOEFL is:617 that's good news the program below shows the contents of the above file Test.dat on the screen:[CPP]View Plaincopy
Post-run Screen display: Your score of the TOEFL is:617 that's good news
4. Clear and Set file buffers
(1). Clear the File buffer function:
int fflush (FILE *stream);
int Flushall ();
The Fflush () function clears the contents of the file buffer pointed to by the stream, which is used to clear the buffer immediately after writing some data, so as to avoid damaging the original data when it is accidentally manipulated. Flushall () Clears the file buffers that correspond to all open files.
(2). Setting the 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, without using the fopen () function to open the default buffer set by the file. For the Setbuf () function, buf indicates that the buffer length is determined by the value of the macro bufsize defined in the header file Stdio.h, with a default value of 512 bytes. When the selected buf is empty, the SETBUF function causes the file I/O to be buffered. For the SETVBUF function, a buffer is allocated by the malloc function. The parameter size indicates the length of the buffer (must be greater than 0), and the parameter type represents the type of the buffer, and the value can take the following value: The type value means that the _IOFBF file is fully buffered, that is, the buffer is full before it can read and write to the file _iolbf file line buffer, when the buffer receives a newline character, In order to read and write to the file _IONBF file does not buffer, at this time ignore the value of buf,size, directly read and write files, no longer through the file buffer buffer.
5. Random Read and write function of the file
The characters/strings of the files described above are read and written in the order of the files, i.e. they are always read and written from the beginning of the file. This obviously does not meet our requirements, C language provides the movement of file pointers 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 if the move succeeds, or return a non-0 value. The fseek () function is used to move the file pointer from origin to offset byte, where Origin points to the following:
Origin value represents the exact location
Seek_set 0 File Start
Seek_cur 1 file pointer current position
Seek_end 2 File Footer
For example: Fseek (fp,10l,0); Move the file pointer from the beginning of the file to the 10th byte, since the offset parameter requirement is a long integer number, so its number is followed by L.
Fseek (fp,-15l,2); Move the file pointer forward 15 bytes 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 flow pointer, each data item is of size bytes, the Read Nitems data item is stored in the memory buffer pointed to by the PTR pointer, and when the Fread () function is executed, the file pointer moves backwards as the number of bytes read , the position at which the last move ends equals the number of bytes actually read out. After the execution of the function, the number of data items actually read is returned, which is not necessarily equal to the set Nitems, because if there are not enough data items in the file, or if there is an error in the middle of the read, the number of data items returned will be less than the set Nitems. When the return number is not equal to nitems, it can be checked with the feof () or ferror () function. The fwrite () function takes a Nitems data item of size bytes from the buffer pointed to by the PTR, writes to the file that the stream pointer stream points to, and after performing the 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 operation is complete, the number of data items written is also returned.
Ii. Reading and writing of non-standard files
This type of function was first used for UNIX operating systems, the ANSI standard is undefined, but sometimes it is often used, and DOS 3.0 or later 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 is the opening file, whose invocation format is: int open (char *filename, int access); This function means that a 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 modifier, and both are connected in a "(" or ") manner. Modifiers can have more than one, but the basic mode can have a single. The rules of access--------------------------------------------------------basic schema meaning modifiers---------------------------------- ----------------------O_rdonly Read-only o_append file pointer to the end o_wronly write-only o_creat file does not exist when the file is created, property is O_rdwr read/write O_trunc if the file exists in the basic mode property The length is reduced to 0, the property is invariant o_binary open a binary file O_text open a text file---------------------------------------------------------open () function opens successfully , the return value is the value of the file descriptor (non-negative), otherwise returns-1. The function of the close () function is to close the file opened by the open () function in the form of: int close (int handle); This function closes the file description Word handle attached file.
2. Read and Write functions
int read (int handle, void *buf, int count);
The read () function reads the count bytes from a file connected to the handle (file descriptor) into the buffer referred to by BUF, the return value is the actual number of bytes read, and 1 indicates an error. Returning 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 BUF to the buffer that is attached to the handle, and the return value is the number of bytes actually written.
3. Random positioning 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, and functions and uses the same as the fseek () function. The call () function is formatted as long tell (int handle); The function returns the current position pointer of the file connected to the handle, with the same function and usage as the Ftell ()
5. The read function and the Write function
Source: Ant-C + + standard programming Antigloss
#include ssize_t read (int filedes, void *buf, size_t nbytes); Return value: The number of bytes read, 0 (read to EOF), 1 (Error) the Read function reads Nbytes bytes from the opened file specified by Filedes to BUF. 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, then the actual read is only 30 bytes, and the Read function returns 30. Using the Read function again at this time will cause read to return 0.
B. When reading from an end device (terminal device), only one line is normally read 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 a pipe or FIFO, the number of bytes in the pipe or FIFO may be less than nbytes.
E. When reading from a record-oriented (record-oriented) device, some record-oriented devices, such as tapes, can return a maximum of one record at a time. F. The signal is interrupted when part of the data is read. The read operation starts with the CFO. Before the successful return, the CFO increments to the actual number of bytes read.
#include ssize_t write (int filedes, const void *buf, size_t nbytes); Return value: The number of bytes written to the file (success);-1 (Error) The Write function writes nbytes byte data to the Filedes, and the data source is BUF. The return value is generally always equal to nbytes, otherwise it is an error. A common cause of error is that disk space is full or exceeds the file size limit. For normal files, the write operation starts with the CFO. If O_append is used when the file is opened, each write writes the data to the end of the file. After a successful write, the CFO increments to the actual number of bytes written.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C language file read and write operation summary
Start building with 50+ products and up to 12 months usage for Elastic Compute Service