C language, file operation summary

Source: Internet
Author: User
Tags fread int size rewind

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:

Example:
    1. FILE *FP;
    2. if ((Fp=fopen ("test","W")) ==null) {
    3. printf ("File cannot be opened/n");
    4. Exit ();
    5. }
    6. Else
    7. printf ("File opened for writing/n");
    8. ......
    9. Fclose (FP);

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:

Example:
    1. if (fclose (FP)!=0) {
    2. printf ("File cannot be closed/n");
    3. Exit (1);
    4. }
    5. Else
    6. printf ("File is now closed/n");

You can use the Fcloseall () function when you open multiple files and close them simultaneously, which closes all open files in the 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 when executed: N=fcloseall (); , n should be 4.

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.

Example:
  1. #include "stdio.h"
  2. #include <stdlib.h>
  3. int main () {
  4. FILE *FP;
  5. Char ch;
  6. if ((Fp=fopen ("MyFile.txt","R")) ==null) {
  7. printf ("file cannot be opened/n");
  8. Exit (1);
  9. }
  10. While ((CH=FGETC (FP))!=eof)
  11. FPUTC (ch,stdout);
  12. Fclose (FP);
  13. }

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 the fgets () 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:

Example:
  1. #include "stdio.h"
  2. int main () {
  3. FILE *FP;
  4. Char str[128];
  5. if ((Fp=fopen ("test.txt","R")) ==null) {
  6. printf ("Cannot open file/n"); exit (1);
  7. }
  8. While (!feof (FP)) {
  9. if (fgets (STR,128,FP)!=null)
  10. printf ("%s", str);
  11. }
  12. Fclose (FP);
  13. }

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:

Example:
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main () {
  4. Char *s="that ' s good news";
  5. int i=617;
  6. FILE *FP;
  7. Fp=fopen ("Test.dat", "w"); / * Create a text file to write only * /
  8. Fputs ("Your score of the TOEFL is", FP); / * Write a string of characters to the built file * /
  9. FPUTC (': ', FP); /* Write a colon to the file you built: */
  10. fprintf (FP, "%d/n", I); / * Write an integer number to the file you built * /
  11. fprintf (FP, "%s", s); / * Write a string to the file you built * /
  12. Fclose (FP);
  13. }

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.

You can use the Ftell and fseek functions to get the size of a file, just move the file pointer to the end of the file, and then use the Ftell. No more demonstrations here.

(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

1. 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.

2. 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 ()

3. The read function and the Write function

Source: Ant-C + + standard programming Antigloss

1. Read

#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.

2. Write

#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.

C language, file operation summary

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.