c Procedures for the processing of files

Source: Internet
Author: User

Cfile read/write

In the previous chapter we explained the standard input and output devices for C language processing. In this chapter we will describe how C programmers can create, open, and close text files or binaries.

A file, whether it is a text file or a binary file, represents a series of bytes. The C language not only provides access to the top-level functions, but also provides the underlying (OS) call to process the files on the storage device. This chapter will explain important calls to file management.

Open File

You can use the fopen () function to create a new file or open an existing file that initializes an object of type file that contains all the necessary information to control the flow. Here is the prototype for this function call:

*fopen(constChar* filename,constChar*);     

Here,filename is a string that is used to name the file , and the value of the access pattern mode can be one of the following values:

Mode Description
R Opens an existing text file that allows you to read the file.
W Opens a text file that allows writing to the file. If the file does not exist, a new file is created. Here, your program writes the content from the beginning of the file.
A Opens a text file that writes to the file in Append mode. If the file does not exist, a new file is created. Here, your program appends content to the existing file content.
r+ Opens a text file that allows you to read and write files.
w+ Opens a text file that allows you to read and write files. If the file already exists, the file is truncated to zero length, and if the file does not exist, a new file is created.
A + Opens a text file that allows you to read and write files. If the file does not exist, a new file is created. The read starts at the beginning of the file, and the write can only be append mode.

If you are working with a binary file, you need to use the following access mode instead of the above access mode:

"RB","WB","AB","rb+","R+b","wb+","W+b","ab+" ,"a+b"               
Close the file;

In order to close the file, use the fclose () function. The prototype of the function is as follows:

int fclose(*);   

If the file is closed successfully, thefclose () function returns zero, and if an error occurs while closing the file, the function returns EOF. This function, in effect, empties the data in the buffer, closes the file, and frees all the memory used for the file. EOF is a constant defined in the header file stdio.h .

The C Standard library provides a variety of functions to read and write files by character or as a fixed-length string.

Write file

Here is the simplest function to write characters to the stream:

int FPUTC(int c,*);      

The function FPUTC () writes the character value of the parameter C to the output stream pointed to by the FP. If the write succeeds, it returns the characters written, and if an error occurs, it returns EOF. You can use the following function to write a null-terminated string to the stream:

int fputs(constChar*s,*);        

The function fputs () writes the string s to the output stream pointed to by the FP. If the write succeeds, it returns a non-negative value, and EOFis returned if an error occurs. You can also use the int fprintf (file *fp,const char *format, ...) function to write a string to a file. Try the following example:

Note: Make sure that you have the/ tmp directory available, and if it does not exist, you will need to create the directory on your computer first.

#include <stdio.h>Main(){ FILE *fp; FP = Fopen ( "/tmp/test.txt" , );  Fprintf (fp,  "This was testing for fprintf...\n ");  Fputs ( "This was testing for fputs...\n" ,< Span class= "PLN" > Fp);  Fclose (fp               /span>                

When the above code is compiled and executed, it creates a new file test.txtin the/tmp directory and writes two rows using two different functions. Next, let's read the file.

Read file

Here is the simplest function to read a single character from a file:

int fgetc(*);   

The fgetc () function reads a character from the input file that the FP points to. The return value is the read character, and EOFis returned if an error occurs. The following function allows you to read a string from the stream:

Char*fgets(char*buf,int n,*);     

The function fgets () reads n-1 characters from the input stream that the FP points to. It copies the read string to the buffer bufand appends a null character to the end of the string.

If the function encounters a newline character ' \ n ' or EOF at the end of the file before the last one is read, only the characters that are read are returned, including the line feed. You can also use the int fscanf (file *fp, const char *format, ...) function to read a string from a file, but when the first space character is encountered, it stops reading.

#include <stdio.h>Main(){FILE*Fp; CharBuff[255];Fp=fopen("/tmp/test.txt", "R");fscanf(Fp, '%s ',Buff);Printf("1:%s\n",Buff);Fgets(Buff, 255, (file*) fp);  printf< Span class= "pun" > ( "2:%s\n" , buff  Fgets (buff, 255,  (file *) fp);  Printf ( "3:%s\n" , buff  Fclose (fp               /span>                

When the above code is compiled and executed, it reads the file created in the previous section, producing the following results:

1:This2: are for fprintf ... 3:            This was for fputs ... 

First, thefscanf () method only reads this because it encounters a space behind it. Second, call fgets () to read the remaining portions until the end of the line. Finally, call fgets () to read the second line completely.

Binary I/O functions

The following two functions are used in binary input and output:

size_tFread(void *Ptr, size_t Size_of_elements, size_t  Number_of_elements, FILE * a_file);  size_t Fwrite (const< Span class= "PLN" > void *ptr , size_t size_of_elements , size_t number_of_elements , FILE *a_file   

Both of these functions are used to read and write a block-usually an array or struct.

c Procedures for the processing of files

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.