C File Operations

Source: Internet
Author: User

Basic concepts of documents
The so-called "file" refers to an ordered set of related data. This dataset has a name, called the file name. In fact, in the previous chapters we have used the files many times, such as source program file, target file, executable file, library file (header file) and so on. Files typically reside on external media, such as disks, and are only transferred into memory when they are used. Different types of files can be categorized from different angles. From the user's point of view, the file can be divided intoNormal fileAndDevice FilesTwo kinds.

   Normal fileRefers to an ordered set of data residing on a disk or other external media, either as a source file, a target file, an executable program, or as a set of raw data to be entered for processing, or as a result of a set of outputs. For source files, target files, executable programs can be calledProgram Files, the input and output data can be calledData Files。

   Device Filesrefers to the various external devices associated with the host, such as monitors, printers, keyboards, and so on. In the operating system, the external device is also treated as a file for management, and their input, output is equivalent to the disk file read and write. Typically the display is defined asStandard output File, the general display of information on the screen is output to the standard output file. This type of output is the Printf,putchar function that is often used earlier. The keyboard is usually specifiedStandard input File, typing from the keyboard means entering data from a standard input file. The Scanf,getchar function is part of this type of input.

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

ASCII files are also referred to as text files, which are stored on disk with one byte per character for the corresponding ASCII code. For example, the number 5678 is stored in the following form:
ASC code: 00110101 00110110 00110111 00111000
Decimal code: 5 6 7 8
A total of 4 bytes are consumed. ASCII files can be displayed on the screen by character, such assource Program Filesis an ASCII file, with the DOS command type to display the contents of the file. Because it is displayed by character, it can read the contents of the file.

Binary files are stored as binary encoding methods for storing files. For example, the number 5678 is stored in the form of: 00010110 00101110 is only two bytes (Int16)。 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".

This chapter discusses various operations such as opening, closing, reading, writing, and positioning of streaming files.File PointersIn the C language, a pointer variable is used to point to a file, which is called a file pointer. A file pointer allows you to perform various operations on the file it refers to. The general form of the definition description file pointer is: file* pointer variable identifier, where file should be uppercase, which is actually a system-definedstructure, the structure containsinformation such as file name, file status, and current location of the file。 You do not have to care about the details of the file structure when writing the source program. For example: File *fp, which indicates that the FP is a pointer variable pointing to the file structure, the FP can find the structure variable that holds the information of the document, then finds the file by the information provided by the structure variable, and implements the operation of the file. It is customary to refer to FP as a pointer to a file in general. Open and close files are opened before read and write operations, and are closed before they are used. 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 languages, file operations are done by library functions. The main file manipulation functions are described in this chapter.

File Open functionfopen

   fopenfunction is used to open a file, the general form of invocation is: The file pointer name =fopen (file name, using the method) where the "file pointer name" must be described as the file type of the pointer variable, "file name" is an open file name. "Use file Mode" refers to the type of file and the 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.
Meaning of the way the file is used
"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. When 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. 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, and the program will continue to execute only when the user taps any key from the keyboard, so the user can use this wait time to read the error prompt. Execute exit (1) to exit the program after tapping the key.

6. When a text file is read into memory, the ASCII code is converted to binary code, and the file is written in text to the disk, the binary code is converted to ASCII code, so the text file read and write to spend more time to convert. There is no such conversion to read and write binary files.

7. Standard input file (keyboard), standard output file (display), standard error output (Error message) is open by the system, can be used directly. File Close function fclose file once used, the closed file function is applied to close the file to avoid errors such as data loss of the file.

fclose function

The general form of invocation is: fclose (file pointer); For example:
Fclose (FP); When the close file operation is completed normally, the Fclose function returns a value of 0. Returning a value other than 0 indicates an error occurred. 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. Using the above functions requires the inclusion of the header file stdio.h. character reading and writing functions fgetc and FPUTC character reading and writing functions are read and write functions in characters (bytes). Each time a character can be read from a file or written to a file.

One, 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: a 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 a character can also not assign a value to a character variable, for example: fgetc (FP), but the read-out character cannot be saved.

3. There is a position pointer inside the file. The current read and write bytes used to point to the file. When the file is opened, the pointer always points to the first byte of the file. When you use the FGETC function, the position pointer moves backwards by one byte. Therefore, multiple characters can be read by using the FGETC function multiple times in succession. Note that file pointers and positional pointers inside files are not the same thing. The file pointer is to the entire file, you must define the description in the program, as long as you do not reassign the value, the value of the file pointer is constant. The position pointer inside the file indicates the current read and write location inside the file, each time it is read and written, the pointer moves backwards, it does not need to define the description in the program, but is automatically set by the system.

[Example 10.1] read the file e10-1.c, output on the screen.
#include <stdio.h>
Main ()
{
FILE *FP;
Char ch;
if ((Fp=fopen ("e10_1.c", "RT")) ==null)
{
printf ("Cannot open file strike any key exit!");
Getch ();
Exit (1);
}
CH=FGETC (FP);
while (ch!=eof)
{
Putchar (CH);
CH=FGETC (FP);
}
Fclose (FP);
}
The function of this example is to read the characters from the file and display them on the screen. The program defines the file pointer fp, opens the file "e10_1.c" as a read text file, and makes the FP point to the file. If there is an error opening the file, give the prompt and exit the program. The 12th line of the program reads a character and then enters the loop, as long as the read character is not the end-of-file flag (at the end of each file, EOF) displays the character on the screen and then reads the next character. Every time you read, the position pointer inside the file moves backwards by one character, and when the file ends, the pointer points to EOF. Executing this program will display the entire file.

Second, the character function fputc

The function of the FPUTC function is to write a character to the specified file, in the form of a function call: FPUTC (character amount, file pointer), where the amount of characters to be written can be a character constant or a variable, for example: FPUTC (' a ', FP), meaning that the character A is written to the file pointed to by the FP.

The use of the FPUTC function should also explain several points:
1. The file to be written can be used, written, read/write, append mode open, write or read or write to open an existing file will clear the original file content, write characters from the beginning of the file. To keep the contents of the original file, you want to write the characters to start at the end of the file, you must open the file in Append mode. The file that was written to does not exist, it is created.

2. Each write one character, the internal position of the file pointer moves backwards one byte.

3. The FPUTC function has a return value, such as if the write succeeds, returns a written character, or an EOF is returned. You can use this to determine if the write was successful.

[Example 10.2] input a line of characters from the keyboard, write a file, and then read out the contents of the file displayed on the screen.
#include <stdio.h>
Main ()
{
FILE *FP;
Char ch;
if ((Fp=fopen ("string", "wt+")) ==null)
{
printf ("Cannot open file strike any key exit!");
Getch ();
Exit (1);
}
printf ("Input a string:\n");
Ch=getchar ();
while (ch!= ' \ n ')
{
FPUTC (CH,FP);
Ch=getchar ();
}
Rewind (FP);
CH=FGETC (FP);
while (ch!=eof)
{
Putchar (CH);
CH=FGETC (FP);
}
printf ("\ n");
Fclose (FP);
}
The 6th line of the program opens a file string as a read-write text file. The 13th line of the program reads a character from the keyboard into a loop, and when the read-in character is not a carriage return, the character is written to the file, and then the next character is read from the keyboard. Each character is entered, and the internal position pointer moves backwards by one byte. After writing, the pointer is pointing to the end of the file. If you want to read the file from the beginning, you need to move the pointer to the file header, the 19th line of the program Rewind function is used to move the internal position of the FP file pointer to the file header. Line 20th to 25th is used to read a line in the file.

[Example 10.3] The file that identifies the previous file name in the command line argument is copied to the file that is identified by the latter file name, such as only one file name in the command line that writes the file to a standard output file (display).
#include <stdio.h>
Main (int Argc,char *argv[])
{
FILE *FP1,*FP2;
Char ch;
if (argc==1)
{
printf ("has not enter the file name strike any key exit");
Getch ();
Exit (0);
}
if ((Fp1=fopen (argv[1], "RT")) ==null)
{
printf ("Cannot open%s\n", argv[1]);
Getch ();
Exit (1);
}
if (argc==2) fp2=stdout;
else if ((Fp2=fopen (argv[2], "wt+")) ==null)
{
printf ("Cannot open%s\n", argv[1]);
Getch ();
Exit (1);
}
while ((Ch=fgetc (FP1))!=eof)
FPUTC (CH,FP2);
Fclose (FP1);
Fclose (FP2);
}
This procedure is the main function with parameters. The program defines two file pointers, FP1 and FP2, pointing to the files given in the command line arguments. If the file name is not given in the command line arguments, a prompt is given. The 18th line of the program indicates that if only one file name is given, FP2 points to the standard output file (that is, the monitor). Lines 25th to 28 of the program are read out of the characters in file 1 and sent to file 2 with a looping statement. When running again, a file name (created by example 10.2) is given, so output to the standard output file stdout, which displays the contents of the file on the display. The third run, which gives two file names, reads the contents of the string and writes it to OK. The DOS command type displays the contents of OK: string read-write function fgets and fputs

The function of reading a string function Fgets function is to read a string into a character array from the specified file, in the form of a function call: fgets (character array name, n, file pointer), where n is a positive integer. Indicates that a string that is read from a file does not exceed n-1 characters. After the last character read, add the string end flag ' \ s '. For example: Fgets (STR,N,FP), the meaning is to read from the file referred to in the FP n-1 characters into the character array str.
[Example 10.4] reads a string containing 10 characters from the e10_1.c file.
#include <stdio.h>
Main ()
{
FILE *FP;
Char str[11];
if ((Fp=fopen ("e10_1.c", "RT")) ==null)
{
printf ("Cannot open file strike any key exit!");
Getch ();
Exit (1);
}
Fgets (STR,11,FP);
printf ("%s", str);
Fclose (FP);
}
This example defines a character array str total of 11 bytes, after opening the file e101.c as a read text file, read out 10 characters into the STR array, in the last cell of the array will be added ' \ ', and then display the output str array on the screen. The output of the 10 characters is exactly the first 10 characters of the example 10.1 program.

The Fgets function has a two-point description:
1. Before the n-1 characters are read out, if a newline character or EOF is encountered, the readout ends.
2. The Fgets function also has a return value whose return value is the first address of a character array.

Second, write String function fputs

The function of the fputs function is to write a string to the specified file in the form of: fputs (string, file pointer) where the string can be a string constant, or it can be a character array name, or a pointer variable, for example:
Fputs ("ABCD", FP);
The meaning is to write the string "ABCD" into the file referred to by the FP. [Example 10.5] appends a string to the file created in Example 10.2.
#include <stdio.h>
Main ()
{
FILE *FP;
Char ch,st[20];
if ((Fp=fopen ("string", "at+")) ==null)
{
printf ("Cannot open file strike any key exit!");
Getch ();
Exit (1);
}
printf ("Input a string:\n");
scanf ("%s", ST);
Fputs (ST,FP);
Rewind (FP);
CH=FGETC (FP);
while (ch!=eof)
{
Putchar (CH);
CH=FGETC (FP);
}
printf ("\ n");
Fclose (FP);
}
This example requires the string to be written at the end of the string file, so the file string is opened in line 6th of the program to append a read-write text file. It then enters a string and writes it to the file string using the Fputs function. In program 15, use the rewind function to move the file's internal position pointer to the top of the file. Then enter the loop to display the entire contents of the current file one by one.

Data block read-write function fread and fwrite

The C language also provides read and write functions for the entire block of data. Can be used to read and write a set of data, such as an array element, the value of a struct variable, and so on. The general form of a read block function call is: Fread (BUFFER,SIZE,COUNT,FP); The general form of a write block function call is: fwrite (BUFFER,SIZE,COUNT,FP); Where buffer is a pointer to the Fread function, which represents the first address that holds the input data. In the Fwrite function, it represents the first address that holds the output data. A size represents the number of bytes of data block. Count represents the number of block blocks of data to read and write. The FP represents a file pointer.
For example:
Fread (FA,4,5,FP); The meaning is that from the file referred to in the FP, each read 4 bytes (a real number) into the real group FA, read 5 consecutive times, that is, read 5 real numbers into FA.
[Example 10.6] input two student data from the keyboard, write a file, and then read the data of the two students displayed on the screen.
#include <stdio.h>
struct STU
{
Char name[10];
int num;
int age;
Char addr[15];
}BOYA[2],BOYB[2],*PP,*QQ;
Main ()
{
FILE *FP;
Char ch;
int i;
Pp=boya;
Qq=boyb;
if ((Fp=fopen ("Stu_list", "wb+") ==null)
{
printf ("Cannot open file strike any key exit!");
Getch ();
Exit (1);
}
printf ("\ninput data\n");
for (i=0;i<2;i++,pp++)
scanf ("%s%d%d%s", pp->name,&pp->num,&pp->age,pp->addr);
Pp=boya;
Fwrite (pp,sizeof (struct stu), 2,FP);
Rewind (FP);
Fread (qq,sizeof (struct stu), 2,FP);
printf ("\n\nname\tnumber age addr\n");
for (i=0;i<2;i++,qq++)
printf ("%s\t%5d%7d%s\n", qq->name,qq->num,qq->age,qq->addr);
Fclose (FP);
}
This example program defines a structure Stu, illustrates two arrays of structures Boya and BOYB, and two structure pointer variables pp and QQ. PP pointing boya,qq to Boyb. The program line 16th reads and writes the binary file "Stu_list", enters two student data, writes to the file, then moves the file's internal position pointer to the top of the file, and reads out two student data to display on the screen.

Format read-write functions fscanf and fprintf

The FSCANF function, the fprintf function, is similar to the function of the scanf and printf functions used earlier, and is a formatted read-write function. The difference between the two is that the FSCANF function and the read-write object of the fprintf function are not keyboards and monitors, but disk files. The invocation formats for these two functions are: fscanf (file pointers, format strings, input table columns), fprintf (file pointers, format strings, output table columns), for example:
FSCANF (FP, "%d%s", &i,s);
fprintf (FP, "%d%c", j,ch);
The problem of example 10.6 can also be completed with the FSCANF and fprintf functions. The modified program is shown in example 10.7.
[Example 10.7]
#include <stdio.h>
struct STU
{
Char name[10];
int num;
int age;
Char addr[15];
}BOYA[2],BOYB[2],*PP,*QQ;
Main ()
{
FILE *FP;
Char ch;
int i;
Pp=boya;
Qq=boyb;
if ((Fp=fopen ("Stu_list", "wb+") ==null)
{
printf ("Cannot open file strike any key exit!");
Getch ();
Exit (1);
}
printf ("\ninput data\n");
for (i=0;i<2;i++,pp++)
scanf ("%s%d%d%s", pp->name,&pp->num,&pp->age,pp->addr);
Pp=boya;
for (i=0;i<2;i++,pp++)
fprintf (FP, "%s%d%d%s\n",pp->name,pp->num,pp->age,pp->
addr);
Rewind (FP);
for (i=0;i<2;i++,qq++)
FSCANF (FP, "%s%d%d%s\n", qq->name,&qq->num,&qq->age,qq->addr);
printf ("\n\nname\tnumber age addr\n");
Qq=boyb;
for (i=0;i<2;i++,qq++)
printf ("%s\t%5d%7d%s\n", Qq->name,qq->num, Qq->age,
QQ-&GT;ADDR);
Fclose (FP);
}
Compared to example 10.6, the FSCANF and fprintf functions in this program can read and write only one structure array element at a time, so a looping statement is used to read and write all the array elements. Also note that the pointer variable pp,qq because the loop changes their values, so in the program's 25 and 32 rows they are re-assigned to the array's first address.

C File Operations

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.