C Language file reading and writing

Source: Internet
Author: User
Tags fread rewind

From the file encoding method, the file can be divided into ASCII code files and binary code file two kinds.

ASCII The file is also called a text file , which is stored on disk with one byte per character for the corresponding ASCII code. ASCII files can be displayed on the screen by character.

Binary files are stored as binary encoding methods for storing files. Binary files can also be displayed on the screen, but their contents are unreadable.

When processing these files, the C system does not distinguish between types, which are treated as character streams and processed in bytes. The start and end of a stream of input and output characters is controlled only by program control and not by physical symbols such as carriage returns. Therefore, this file is also referred to as a "streaming file".

1. Opening and closing of files

The file must be opened before reading and writing, and will be closed when it is finished. The so-called open file, is actually to establish a variety of information about the file, and the file pointer to the file for other operations. Closing a file breaks the link between the pointer and the file, and it prevents the file from being manipulated.

In the C language, file operations are done by library functions. The main file manipulation functions are described in this chapter.

In the stdio.h file, there is a struct-type of files.

typeof struct

{short level;

unsigned flags;

Char FD;

unsigned char hold;

Short bsize;

unsigned char *buffer;

unsigned ar *curp;

unsigned istemp;

Short token;

} FILE;

You can define an array of file types, for example: file f[5];

You can define a file type pointer, for example: file *fp;--fp A struct variable that points to a file.

If there are n files, it is generally necessary to set n pointer variables so that they point to n files respectively to achieve access to the file.

1.1 Opening of the file (fopen function)

The fopen () function is used to open a file whose general form of invocation is:

File pointer name =fopen (filename, using file mode);

Where the "file pointer name" must be a pointer variable that is described as a file type;

"File name" is the filename of the file being opened;

"Use file Mode" refers to the type of file and operational requirements;

"File name" is a string constant or an array of strings.

For example:

FILE *FP;

fp= ("File A", "R");

The meaning is to open file A in the current directory, only allow "read" operation, and make FP point to the file.

Another example:

FILE *FPHZK

fphzk= ("C:\\hzk16", "RB")

The significance is to open the C drive disk root directory of the file hzk16, which is a binary file, only allowed to read in binary mode. The first of the two backslashes "\ \" represents an escape character, and the second represents the root directory.

There are 12 ways to use the file, and the symbols and meanings are given below.

How files are used

Significance

"RT" read-only open a text file, allowing only read data
"WT" only writes Open or create a text file, allowing only write data
"At" Appends open a text file and writes data at the end of the file
"RB" read-only open a binary file, allowing only read data
"WB" only writes open or create a binary file, allowing only write data
"AB" appends open a binary file and writes data at the end of the file
"rt+" read and write open a text file that allows read and write
"wt+" read/write open or create a text file that allows read and write
"at+" read and write open a text file, allow reading, or append data at the end of the file
"rb+" read and write open a binary file that allows read and write
"wb+" read-write open or create a binary file that allows read and write
"ab+" read and write open a binary file, allow reading, or append data at the end of the file

There are several explanations for how the file is used:

1) file usage by r,w,a,t,b,+ Six characters, the meaning of each character is:

R (Read): Read
W (write): Write
A (append): Append
T (text): Literal file, can be omitted without writing
B (banary): binary file
+: Read and Write

2) Where a file is opened with "R", the file must already exist and can only be read from the file.

3) files opened with "W" can only be written to the file. If the open file does not exist, the file is created with the specified file name, and if the open file already exists, the file is deleted and a new file is rebuilt.

4) to append new information to an existing file, you can only open the file in "a" mode. However, the file must be present at this point, or an error will occur.

5) If an error occurs when opening a file, fopen will return a null pointer value of NULL (defined as 0). In the program can use this information to determine whether to complete the work of open files, and corresponding processing. Therefore, the following sections are commonly used to open files:

if ((Fp=fopen ("c:\\hzk16", "RB") ==null)
{printf ("\nerror on Open c:\\hzk16 file!");
Getch ();
Exit (1);
}

The meaning of this program is that if the returned pointer is empty, indicating that the hzk16 file under the C packing directory cannot be opened, the message "Error on open c:hzk16file!" is given, and the next line of Getch () is to enter a character from the keyboard but not on the screen. Here, the function of the line is to wait only when the user knocks any key from the keyboard. The Exit function closes all files and terminates the program being executed.

1.2 Closing of files

The Fclose function closes the file:

fclose (file pointer);

For example, Fclose (FP), or EOF (-1) If the return value is 0 if it is closed successfully. You can use the Ferror function to test.

2. Read and Write files

Read and write files are the most commonly used file operations. There are several functions for reading and writing files in the C language:

• character reading and writing functions: Fgetc and FPUTC

• String Read and write functions: Fgets and Fputs

• Data block Read and write functions: Freed and Fwrite

• Formatted read-write functions: fscanf and Fprinf

The following are presented separately. The use of the above function requires that the header file <stdio.h> be included.

2.1 character read and write functions fgetc and FPUTC

A character read-write function is a read-write function in characters (bytes). Each time a character can be read from a file or written to a file.

1. read character function fgetc

The function of the FGETC function is to read a character from the specified file, in the form of a function call:

Character variable =fgetc (file pointer);

For example:

CH=FGETC (FP);

The meaning is to read a character from an open file FP and feed it into ch.

There are several explanations for the use of the FGETC function:

1) in the FGETC function call, the read file must be opened in read or read-write mode.

2) The result of reading the character can also not assign a value to the character variable, fgetc (FP);

The function returns a file end flag, EOF (that is,-1). If you want to read a disk file into characters and display them on the screen, you can use:

CH=FGETC (FP);

while (ch!=eof)

{Putchar (CH);

CH=FGETC (FP);

}

If the number that is being read is exactly-1, which is exactly the EOF value, to solve this problem, provide a feof function to determine whether the file really ends. If the file ends, the value of the feof (FP) function is 1, otherwise 0. The cycle condition is changed to:

while (!feof (FP))

{Putchar (CH);

CH=FGETC (FP);

}

However, the characters you read cannot be saved.

2. Write character function Fputc

The function of the FPUTC function is to write a character to the disk file.

FPUTC (character amount, file pointer), for example:

FPUTC (' A ', FP);

The use of its meaning PUTC function should also explain several points:

The FPUTC function has a return value that returns a write character if the write succeeds, or an EOF is returned. This can be used to determine the write character, write a file, and then read out the contents of the file displayed on the screen.

Example 1: Enter some characters from the keyboard and write to the disk one after the other until you enter a "#".

#include "stdio.h"

#include "Stdlib.h"

Main ()

{

FILE*FP;

CHARCH,FILENAME[10];

scanf ("%s", filename);

if ((Fp=fopen (filename, "w")) ==null)

{

printf ("Cannot openfile\n");

Exit (0);

}

Ch=getchar ();

Ch=getchar ();

while (ch!= ' # ')

{

FPUTC (CH,FP);

Putchar (CH);

Ch=getchar ();

}

Putchar (10);

Fclose (FP);

}

Example 2 copies the information from one disk file to another disk file.

#include "stdio.h"

#include "Stdlib.h"

Main ()

{

File*in,*out;

CHARCH,INFILE[10],OUTFILE[10];

printf ("Please enter the file name to be copied: \ n");

scanf ("%s", infile);

printf ("Please enter copy to file name: \ n");

scanf ("%s", outfile);

if ((In=fopen (infile, "R")) ==null)

{

printf ("Cannot openinfile\n");

Exit (0);

}

if ((Out=fopen (outfile, "w")) ==null)

{

printf ("Cannot openoutfile\n");

Exit (0);

}

while (!feof ()) FPUTC (Fgetc (in), out);

Fclose (in);

Fclose (out);

}

2.2 fread function and fwrite function

Used to read a set of data, such as a real number or the value of a struct variable. The invocation form is:

Fread (BUFFER,SIZE,COUNT,FP)

Fwrite (BUFFER,SIZE,COUNT,FP)

Where: Buffer is a pointer to Fread, which is the storage address of the read-in data. The fwrite is the address of the data to be output.

Size: Number of bytes to read and write

Count: Number of size bytes of data item to read and write

fp: file-type pointer.

EG:FP (F,4,2,FP); The file pointed to by--FP reads in 2 4-byte data and stores it in the array F.

Consider the following structure:

struct Student_type

{

CHARNAME[10];

Intnum;

Intage

CHARADDR[30];

}STUD[40];

Assuming that the above student data is stored in a disk file, you can read the data for 40 students with the following for statement and Fread function:

for (i=0;i<40;i++)

Fread (&stud[i],sizeof (Structstudent_tpye), 1,FP);

Similarly, you can use the For statement and the Fwrite function to output student data in memory to a disk file:

for (i=0;i<40;i++)

Fwrite (&stud[i],sizeof (Structstudent_tpye), 1,FP);

If the Fread or Fread function call succeeds, the function returns a value of count, which is the complete number of input or output data items.

"Example 3" writes two records to a file

#include <stdio.h>

#include <stdlib.h>

struct record

{CHARNAME[10];

Intage

};

int main (void)

{struct record array[2] ={{"Ken", "{Knuth", 28}};

FILE *fp= fopen ("Recfile", "w");

if (FP ==null)

{

Perror ("Open filerecfile");

Exit (1);

}

Fwrite (array, sizeof (struct record), 2, FP);

Fclose (FP);

Return0;

}

Found that the generated file Recfile cannot be opened directly.

Reason: We think of a structrecord structure as a record, because there are padding bytes in the structure, each record accounts for 12 bytes, two records are written to the file 24 bytes. The Recfile file generated by the program is a binary file, not a text file, because it preserves not only character data, but also integer data 24 and 28 (shown in octal in the output of the OD command as 030 and 034).

Read the contents of the file Recfile through the READREC program, stating that the WRITEREC program does record a successful write to Recfile.

Example 4 reads the record written in Example 3.

#include <stdio.h>

#include <stdlib.h>

struct record

{CHARNAME[10];

Intage

};

int main (void)

{struct RECORDARRAY[2];

FILE *fp= fopen ("Recfile", "R");

if (FP ==null)

{

Perror ("Open filerecfile");

Exit (1);

}

Fread (array, sizeof (struct record), 2,FP);

printf ("Name1:%s\tage1:%d\n", array[0].name,array[0].age);

printf ("Name2:%s\tage2:%d\n", array[1].name,array[1].age);

Fclose (FP);

Return0;

}

fwrite examples of applications and fread:

1. Write a string to the file:

Char*str= "Hello,i am a Test program!";

Fwrite (str,sizeof (str), strlen (str), FP)

2. Write a character array to the file:

Charstr[]={' A ', ' B ', ' C ', ' d ', ' e '};

Fwrite (Str,sizeof (char), sizeof (str), FP)
3. Write an integer array to the file:
INTA[]={12,33,23,24,12};
The number of array elements is calculated first Nmemb, then
Fwrite (a,sizeof (int), NMEMB,FP)
Note: Since the file generated by the program is a binary file rather than a text file, therefore, the expression of integers is different without machines,
Therefore, the build file cannot be opened directly. You can verify that the data is written to the file by using the Fread function.

3. fprintf function and fscanf function

Like the printf function and the scanf function, the only difference is that the fprintf function and the FSCANF function read and write to the object not the terminal but the disk file.

fprintf (file pointers, format strings, output table columns);

FSCANF (file pointer, format string, input table column);

For example:

fprintf (FP, "%d,%6.2f", i,t);

Function: Outputs the values of the shape variable i and the real variable T in the format%d and%6.2f to the file pointed to by the FP.

FSCANF (FP, "%d,% F", &i,&t);

"Example 5"

#include "stdio.h"

#include "Stdlib.h"

void Main ()

{

inti=10;

floatt=3.14;

FILE*FP;

if ((Fp=fopen ("Example_5.txt", "W")) ==null)

printf ("Cannot open file\n");

fprintf (FP, "%d,%6.2f", i,t);

}

4. Document Location

1) Rewind function: Returns the position pointer back to the beginning of the file, with no return value for this function.

Example 6 has a disk file that, for the first time, displays its contents on the screen and copies it to another file the second time.

#include "stdio.h"

void Main ()

{

FILE*FP1,*FP2;

Fp1=fopen ("file1.c", "R");

Fp2=fopen ("File2", "w");

while (!feof (FP1)) Putchar (Getc (FP1));

Rewind (FP1);

while (!feof (FP1)) PUTC (Getc (FP1), FP2);

Fclose (FP1);

Fclose (FP2);

}

2) fseek function: Read and write randomly in the order specified.

fseek (file type pointer, displacement amount, starting point)

Starting point: 0-file start position; 1-current position; 2-End of file

Fseek (fp,100l,0); Move the position pointer to 100 bytes from the head of the file

Fseek (fp,50l,1); Move the position pointer to 50 bytes from the current position

Fseek (fp,-10l,2); Back 10 bytes from the end of the file with the position pointer

Example 7 contains 10 students ' data on a disk file. Requires the 1th, 3, 5, 7, and 9 student data to be entered into the computer and displayed on the screen.

#include "stdio.h"

#include "Stdlib.h"

#define SIZE 5

struct student

{

CHARNAME[10];

Intnum;

Intage;

Charsex;

}stud[size];

void Main ()

{

Inti

FILE*FP;

if ((Fp=fopen ("Stud_data", "RB")) ==null)

{

printf ("Cannot open file\n");

Exit (0);

}

for (i=0;i<size;i+=2)

{

Fseek (fp,i*sizeof (struct student), 0);

Fread (&stud[i],sizeof (struct student), 1,FP);

printf ("%s%d%d%c\n", stud[i].name,stud[i].num,stud[i].age,stud[i]. Sex);

}

Fclose (FP);

}

5. Error detection

ferror function: When invoking various input and output functions, if an error occurs, you can also check with the Ferror function in addition to the function return value that reflects the error.

Feeror (FP); A return value of 0 indicates an error, and a return of a value other than 0 indicates an error.

The initial value of the Feeror function is automatically set to 0 when the fopen function is executed.

Clearerr function: Set the file error flag and file end flag to 0.

Clearerr (FP); Change the value of Ferror (FP) to 0

C Language 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.