Read and Write binary files in C Language

Source: Internet
Author: User

First, we will introduce the functions. We will use three functions in total: fopen, fread, and fwrite. The binary read/write order is to use fopen to open the read/write file in binary mode, and then use the fread and fwrite functions to write data to the binary file. Let's take a look at the source code of a copy program:

Copy. c:
# Include <stdio. h>

# Include <stdlib. h>


# Define MAXLEN 1024


Int main (int argc, char * argv [])

{

If (argc <3)

{

Printf ("usage: % s \ n", argv [0], "infile outfile ");

Exit (1 );

}

FILE * outfile, * infile;

Outfile = fopen (argv [2], "wb ");

Infile = fopen (argv [1], "rb ");

Unsigned char buf [MAXLEN];

If (outfile = NULL | infile = NULL)

{

Printf ("% s, % s", argv [1], "not exit \ n ");

Exit (1 );

}

Int rc;

While (rc = fread (buf, sizeof (unsigned char), MAXLEN, infile ))! = 0)

{

Fwrite (buf, sizeof (unsigned char), rc, outfile );

}

Fclose (infile );

Fclose (outfile );

System ("PAUSE ");

Return 0;

}

 

Now let's talk about this program. The function of this program is to directly copy the content of file 1 to file 2. Pay attention to the return value of fread. This value will be used during fwrite.

The following describes the fopen, fread, and fwrite functions.

Fopen (open a file)
Related Function open, fclose header file # include <stdio. h> define the function FILE * fopen (const char * path, const char * mode). The function description parameter 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 forms of strings:
R: open a read-only file, which 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.
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. Example # include <stdio. h>
Main ()
{
FILE * fp;
Fp = fopen ("noexist", "a + ");
If (fp = NULL) return;
Fclose (fp );
}


Fread (reads data from a file Stream)
Related functions: fopen, fwrite, fseek, and fscanf header file # include <stdio. h> define the size_t fread (void * ptr, size_t size, size_t nmemb, FILE * stream) function. 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. Additional instructions


Example # include <stdio. h>
# Define nmemb 3
Struct test
{
Char name [20];
Int size;
} S [nmemb];
Main ()
{
FILE * stream;
Int I;
Stream = fopen ("/tmp/fwrite", "r ");
Fread (s, sizeof (struct test), nmemb, stream );
Fclose (stream );
For (I = 0; I <nmemb; I ++)
Printf ("name [% d] = %-20 s: size [% d] = % d \ n", I, s [I]. name, I, s [I]. size );
} Run name [0] = Linux! Size [0] = 6
Name [1] = FreeBSD! Size [1] = 8
Name [2] = Windows2000 size [2] = 11


Fwrite (write data to a file Stream)
Related functions: fopen, fread, fseek, and fscanf header file # include <stdio. h> define the size_t fwrite (const void * ptr, size_t size, size_t nmemb, FILE * stream) function. 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. Example # include <stdio. h>
# 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 );
} Execution

See fread ()

 

Fseek () function

Call form:


# Include "stdio. h"

Fseek (file type pointer fp, displacement, starting point );


Function: place the fp-related file position pointer to a specified position.
The "displacement" indicates the number of bytes that the position pointer moves relative to the "starting point. If the displacement is a positive value, it indicates moving from the start point to the end of the file. If the displacement is a negative value, it indicates moving from the start point to the end of the file.

The "Starting Point" cannot be set at will. It can only be one of the three symbolic constants defined in stdio. h:

Start Point

Corresponding number
File Location

SEEK_SET

Starts with 0.
SEEK_CUR

1. Current File Location
SEEK_END

2. End of the file
For example:

Fseek (fp, 50L, 0); or fseek (fp, 50L, SEEK_SET );

It moves the position pointer to 50 bytes away from the file header.

 

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.