C Language Learning Series--file read and write operation detailed

Source: Internet
Author: User
Tags fread function prototype

When the file is opened as specified, you can perform a read and write to the file. The following are categorized by the nature of the file. For text files and binary files of different properties, for text files, can be read and write by characters or read and write to the string, for the binary file, can be read-write or formatted read-write.
1. Read and write characters
C provides fgetc and FPUTC functions to read and write characters to a text file, and the prototype of its function is stored in the stdio.h header file in the following format:
int fgetc (FILE *stream)
The FGETC () function returns a character from the current position of the input stream and moves the file pointer indicator to the next character, and if it is at the end of the file, the function returns EOF, which means that the operation ends and the file should be closed if the read-write file is completed.
int FPUTC (int ch,file *stream)
The FPUTC () function completes writing the value of the character C H to the current position of the specified stream file, and moves the file pointer back one bit. The return value of the FPUTC () function is the value of the character being written, and EOF is returned when an error occurs.

[Example 8-2] The specified text file that is stored on the disk is read from the file, one by one, and then displayed to the screen. With the parameter main (), the specified disk file name is given by the command-line method via the keyboard.
#include <stdio.h>
int main (int size,char *argv[])
{
Char ch;
FILE *FP;
int i;
if ((Fp=fopen (argv[1], "R")) ==null)/* Open a file referred to by argv[1] */
{
printf ("Not open");
Exit (0);
}
while (CH=FGETC (FP)!=eof)/* read one character from a file and display it to the screen */
Putchar (CH);
Fclose (FP);
}
The program is the main () function of the area parameter, which requires the command line to run, its parameter argc is used to record the number of input parameters, argv is an array of pointers, for storing input parameters of the string, the number of strings by ARGC description. Suppose we specify that the read file name is l8-2.c, and that the contents of the list file are the source program. Compiled and connected to generate executable file L8-2.exe. To run the program L8-2.exe, enter the command line as follows:
C:/tc>l8-2 l8-2.c
The above program runs as a command line with two input parameter strings, namely argv[0]= "C:/tc>l8-2", argv[1]= "l8-2.c", argc = 2. So the open file is l8-2.c. The return value of the fgetc () function is constantly tested in the program, and if the end of the file is read or a read file is faulted, the integer constant EOF of C is returned, with a value of not 0 valid integers. The running output of the program is the source program itself:
C:/tc>l8-2 l8-2.c
#include <stdio.h>
int main (int size,char *argv[])
{
Char ch;
FILE *FP;
int i;
if ((Fp=fopen (argv[1], "R")) ==null)/* Open a file referred to by argv[1] */
{
printf ("Not open");
Exit (0);
}
while (CH=FGETC (FP)!=eof)/* read one character from a file and display it to the screen */
Putchar (CH);
Fclose (FP);
}

[Example 8-3] from the keyboard input characters, stored in the disk file Test.txt:
#i nclude <stdio.h>
Main ()
{
FILE FP; /* Define file variable pointer */
Char ch;
if ((Fp=fopen ("Test.txt", "W")) ==null)/* Open file in write-only mode */
{
printf ("Cannot open file!/n");
Exit (0);
}
while ((Ch=fgetchar ())! = '/n ')/* Just enter the word printable carriage return */
FPUTC (CH,FP)/* Write a file a character */
Fclose (FP);
}
The program writes the specified stream file Test.txt by entering a string that ends with a carriage return from the keyboard, and the file is opened in text-only mode, so the stream file is readable and can be accessed by a variety of character processing tools. Simply put, we can display the contents of a file by using the type command provided by DOS.
To run the program:
I Love china!
In the DOS operating system environment, the Test.txt file is displayed as follows using the type command:
C:/tc> type Test.txt
I Love china!

2. Read and Write strings
C provides a function prototype for reading and writing strings in the stdio.h header file, in the form of a function:
Char *fgets (char *str,int num,file *stream)
The fgets () function reads up to num-1 characters from the stream file stream and puts them in a character array pointed to by Str. The character is read until a carriage return or e O F (file terminator) is met, or the number of characters that are qualified is read in.
int fputs (char *str,file *stream)
The fputs () function writes the string pointed to by STR to the stream file. When the operation succeeds, the function returns a value of 0, and the failure returns a value other than 0.

[Example 8-4] writes a string to the disk and writes a text file Test.txt:
#i nclude<stdio.h>
#i nclude<string.h>
Main ()
{
FILE *FP;
Char str[128];
if ((Fp=fopen ("Test.txt", "W")) ==null)/* Open a write-only text file */
{
printf ("Cannot open file!");
Exit (0);
}
while ((Strlen (gets (str)))!=0)
{/* If the string length is zero, the end */
Fputs (STR,FP); /* Write String */
Fputs ("/n", FP); /* Write carriage return */
}
Fclose (FP); /* Close File */
}
Run the program and write the file from the keyboard by entering a string that is not longer than 1 2 7 characters. If the string length is 0, that is, the empty string, the program ends.
Input: hello!
How does do
good-bye!

At the end of the run, we use the DOS type command list file:
C:/tc>type Test.txt
Hello!
How does do
good-bye!
The empty string entered here is actually a separate carriage return, the reason is that the gets function determines that the end of the string is marked with a carriage return.

[Example 8-5] reads the string from a text file Test1.txt, and then writes the test2.txt to a file.
#i nclude<stdio.h>
#i nclude<string.h>
Main ()
{
FILE *fp1,*fp2;
Char str[128];
if ((Fp1=fopen ("Test1.txt", "R")) ==null)
{/* Open the file as read-only 1 */
printf ("Cannot open file/n");
exit (0);
}
If ((Fp2=fopen ("Test2.txt", "W") ==null)
{/* Open the file in write-only mode 2 */
printf ("Cannot open file/n");
exit (0);
}
while (strlen (Fgets (STR,128,FP1)) >0)
/* The length of the string read back from the file is greater than 0 */
{
fputs (STR,FP2);/* Read the string from file 1 and write to file 2 */< br> printf ("%s", str); /* Display on screen */
}
Fclose (FP1);
Fclose (FP2);
}
The program operates a total of two files, you need to define two file variable pointers, so before you manipulate the file, you should open the two files in the same way as needed (in no particular order), and then close the file after reading and writing. The design process is written to the file at the same time displayed on the screen, so after the program runs, you should see the same text file added to the original file and display the contents of the file on the screen.

3. Formatted read and write
In the previous program design, we introduced the use of the scanf () and printf () functions to format input from the keyboard and format the output on the display. The format of the file read and write is to precede the above function with a letter F becomes fscanf () and fprintf (). Its function call method:
int fscanf (FILE *stream,char *format,arg_list)
int fprintf (FILE *stream,char *format,arg_list)
Where stream is the stream file pointer, the remaining two parameters are exactly the same as the scanf () and printf () usages.

[Example 8-6] to write some formatted data to a text file, and then from the file in the format method to read the display to the screen
On the screen, its formatted data is two student records, including name, school number, and the results of both subjects.
#i nclude<stdio.h>
Main ()
{
FILE *FP;
int i;
struct stu{/* define struct type */
Char name[15];
Char num[6];
float score[2];
}student; /* Description struct variable */
if ((Fp=fopen ("Test1.txt", "W")) ==null)
{/* Open file as Text Only */
printf ("Cannot open file");
Exit (0);
}
printf ("Input data:/n");
for (i=0;i<2;i++)
{
scanf ("%s%s%f%f", Student.name,student.num,&student.score[0],
&AMP;STUDENT.SCORE[1]); /* Input from Keyboard */
fprintf (FP, "%s%s%7.2f%7.2f/n", Student.name,student.num,
STUDENT.SCORE[0],STUDENT.SCORE[1]); /* Write file */
}
Fclose (FP); /* Close File */
if ((Fp=fopen ("Test.txt", "R")) ==null)
{/* Reopen file as text read-only */
printf ("Cannot open file");
Exit (0);
}
printf ("Output from file:/n");
while (FSCANF (FP, "%s%s%f%f/n", student.name,student.num,&student.score[0],student.score[1])!=eof)
/* Read in from File */
printf ("%s%s%7.2f%7.2f/n", Student.name,student.num,
STUDENT.SCORE[0],STUDENT.SCORE[1]); /* Display to screen */
Fclose (FP); /* Close File */
}
Programming a file variable pointer, two times in different ways to open the same file, write and read out the format of data, it is important to write to the file in what format, it must be in what format to read from the file, otherwise, the read out of the data and format control character inconsistent, resulting in data errors. The above program runs as follows:
Input data:
Xiaowan j001 87.5 98.4
Xiaoli j002 99.5 89.6
Output from File:
Xiaowan j001 87.50 98.40
Xiaoli j002 99.50 89.60

The contents of the list file are displayed as:
C:/>type Test.txt
Xiaowan j001 87.50 98.40
Xiaoli j002 99.50 89.60
The file accessed by this program can also be set as a binary file, if the file is opened in the following way:
if ((Fp=fopen ("Test1.txt", "WB")) ==null)
{/* Open file in binary write-only mode */
printf ("Cannot open file");
Exit (0);
}
The effect is exactly the same.

4. Block Reading and writing
There are several ways to read and write files, which cannot be written to a file or read from a file in the form of a complex data type. C language provides a block read and write mode to manipulate the file, so that its array or struct type can be read and write once. The form of a block read-write file function is called:
int fread (void *buf,int size,int count,file *stream)
int fwrite (void *buf,int size,int count,file *stream)
The Fread () function reads the count (number of fields) fields from the stream file that the stream points to, each field is a character length of size, and places them in the array of characters that the B u f (buffer) points to.
The Fread () function returns the number of fields that have actually been read. If the number of fields required to be read by a function call exceeds the number of fields stored in the file, an error or end of file is reached, and the actual operation should be examined.
The fwrite () function writes the count (number of fields) field from the character array pointed to by the BUF (buffer) to the stream to which the stream is pointing, each of which is a size character and returns the number of written segments when the function operation succeeds.
For block-based file reads and writes, it can only be created in binary file format when creating a file.

[Example 8-7] writes formatted data to the disk, and then reads from the file to display to the screen.
#i nclude "Stdio.h"
#i nclude "Stdlib.h"
Main ()
{
FILE *FP1;
int i;
struct stu{/* Define structure body */
Char name[15];
Char num[6];
float score[2];
}student;
if ((Fp1=fopen ("Test.txt", "WB")) ==null)
{/* Open the file in binary write-only mode */
printf ("Cannot open file");
Exit (0);
}
printf ("Input data:/n");
for (i=0;i<2;i++)
{
scanf ("%s%s%f%f", student.name,student.num,&student.score[0],&student.score[1]); /* Enter a record */
Fwrite (&student,sizeof (student), 1,FP1); /* Write files into blocks */
}
Fclose (FP1);
if ((Fp1=fopen ("Test.txt", "RB")) ==null)
{/* re-open file with binary write only */
printf ("Cannot open file");
Exit (0);
}
printf ("Output from file:/n");
for (i=0;i<2;i++)
{
Fread (&student,sizeof (student), 1,FP1); /* block read from File */
printf ("%s%s%7.2f%7.2f/n", student.name,student.num,student.score[0],student.score[1]); /* Display to screen */
}
Fclose (FP1);
}
To run the program:
Input data:
Xiaowan j001 87.5 98.4
Xiaoli j002 99.5 89.6
Output from File:
Xiaowan j001 87.50 98.40
Xiaoli j002 99.50 89.60
In general, for the format of the input data is more complex, we can take the data in various formats as a string input, and then convert the string to the desired format. C provides functions:
int atoi (char *ptr)
float atof (char *ptr)
Long int atol (char *ptr)
They convert strings to integer, real, and long integers, respectively. When used, write the header file that it contains math.h or stdlib.h to the front of the program.

C Language Learning Series--file read and write operation detailed

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.