C language implementation of binary file read and write detailed

Source: Internet
Author: User
Tags exit fread include printf

To introduce the function first, we will use three functions, Fopen,fread,fwrite. The order of binary reads and writes is to open the read-write file in binary mode with fopen, and then use the fread and fwrite two functions to write the data to the binary file. Let's take a look at the source 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%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 to talk about this program, the role of the program is to copy the contents of file 1 directly to file 2, pay attention to the return value of fread, this value needs to be used in fwrite.

The following is a detailed description of the Fopen,fread,fwrite three functions.

fopen (Open file)

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.