Reproduced C language for binary file reading and writing

Source: Internet
Author: User
Tags file copy fread

reproduced in: 1852321I have always felt that binary file read and write is a very easy thing, so has not cared about, recently in writing an HTTP client, the implementation of the file download, found that there is always a problem, later found to be forgotten to write files with binary way, ashamed of very ah. then, in the online search, found through the C language to achieve binary file read and write data incredibly little, which makes me very angry, because although this thing is very simple, but for beginners, often will take a long time to get, once understood, and found that the time spent is not worth, just, Here's an example of a file copy that reads and writes a binary file. First, we will use three functions, Fopen,fread,fwrite. The binary read and write order is to open the read-write file in binary mode with fopen and then write the data to the binary using the fread and fwrite two functions. 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%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 speaking of this program, the role of this program is to copy the contents of the file 1 directly to file 2, note the return value of fread, this value needs to be used in fwrite.

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

fopen (open file)
Related functions Open,fclose
Table header File #include <stdio.h>
Defining functions FILE * fopen (const char * path,const char * mode);
Function description The parameter path string contains the file path and filename to open, and the parameter mode string represents the flow pattern.
ModeThere are several pattern strings:
R to open a read-only file, the file must exist.
r+Open a read-write file that must be present.
WOpen Write-only file, if the file exists, the file length is clear to 0, that is, the contents of the file will disappear. If the file does not exist, the file is created.
w+Open a read-write file, if the file exists, the file length is zero, that is, the contents of the file disappears. If the file does not exist, the file is created.
aOpen the write-only file in an additional way. If the file does not exist, the file will be created, and if the file exists, the data written will be added to the end of the file, that is, the original content of the file will be retained.
A +opens a file that can be read and written in an additional way. If the file does not exist, the file will be created, and if the file exists, the data written will be added to the end of the file, that is, the original content of the file will be retained.
These morphological strings can be added with a B character, such as RB, w+b, or ab+ combinations, and a B character is used to tell the library that the file opened is a binary file, not a plain text file. However, in a POSIX system, including Linux ignores the character. A new file created by fopen () will have a s_irusr| s_iwusr| s_irgrp| s_iwgrp| s_iroth| S_iwoth (0666) permission, this file permission will also refer to the Umask value.
return value When the file is opened successfully, the file pointer to the stream is returned. If the file fails to open, it returns null and the error code exists in errno.
Additional Instructions In general, after opening the file will make some file read or write action, if the file fails to open, the next reading and writing action can not be carried out smoothly, so after fopen () Please make error judgment and processing.
Example #include <stdio.h>
Main ()
{
FILE * FP;
Fp=fopen ("Noexist", "A +");
if (fp= =null) return;
Fclose (FP);
}

fread (reading data from a file stream)
Related functions fopen,fwrite,fseek,fscanf
Table header File #include <stdio.h>
Defining functions size_t fread (void * ptr,size_t size,size_t nmemb,file * stream);
Function description Fread () is used to read data from the file stream. The parameter stream is an open file pointer, and the parameter PTR points to the data space to hold the read in, and the number of characters read is determined by the parameter size*nmemb. Fread () returns the number of Nmemb actually read, and if this value is smaller than the parameter nmemb, the representative may have read the end of the file or an error occurred, and must use feof () or ferror () to determine what happened.
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]=%-20s:size[%d]=%d/n", i,s[i].name,i,s[i].size);
}
Perform name[0]=linux! Size[0]=6
name[1]=freebsd! Size[1]=8
name[2]=windows2000 size[2]=11

fwrite (writes data to a file stream)

Related functions fopen,fread,fseek,fscanf
Table header File #include <stdio.h>
Defining functions size_t fwrite (const void * ptr,size_t size,size_t nmemb,file * stream);
Function description Fwrite () is used to write data to the file stream. The parameter stream is an open file pointer, and the parameter PTR points to the data address to be written, and the number of characters written in total is determined by the parameter size*nmemb. Fwrite () returns the number of Nmemb actually written.
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);
}
Perform Refer to Fread ().

Reproduced C language for binary file reading and writing

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.