C language file operations-file read/write

Source: Internet
Author: User

After the file is opened in the specified working mode, you can read and write the file. The following operations are performed by file type. For different types of text files and binary files, you can read and write files by character or by string. For binary files, you can read and write files in blocks or formatted formats.
1. read/write characters
C provides the fgetc and fputc functions to read and write characters in text files. The prototype of the function is stored in the stdio. h header file. The format is:
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. If it has reached the end of the file, the function returns EOF, which indicates that this operation has ended, if the read/write process is complete, close the file.
Int fputc (int ch, file * Stream)
The fputc () function writes the value of the character c h to the current position of the specified stream file, and moves the file pointer one after. The returned value of the fputc () function is the value of the written characters. If an error occurs, an EOF is returned.

[Example 8-2] Read the specified text files stored on the disk one by one as read/write characters, and then display them on the screen. The main () parameter is used. The specified disk file name is given by the command line through the keyboard.
# I nclude <stdio. h>
Main (argc, argv)
Int argc;
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 a character from the file and display it to the screen */
Putchar (CH );
Fclose (FP );
}
A program is a main () function with the same parameters. It must be run as a command line. The argc parameter is used to record the number of input parameters, and argv is a pointer array used to store input parameter strings, the number of strings is described by argc. Suppose we specify the Read File name as the L8-2.c, And the list file content is the source program. After compilation and connection, the executable file l8-2.exe is generated. Run l8-2.exe. The command line is as follows:
L8-2 L8-2.c C:/TC>
The above program runs as a command line, its input parameter string has two, that is, argv [0] = "C:/TC> l8-2", argv [1] = "L8-2.c ", argc = 2. So open the file is L8-2.c. In the program, the return value of the fgetc () function is continuously tested. If an error occurs at the end of the read file or when an error occurs in the Read File, the return value is the integer constant eof c, whose value is a non-zero valid integer. The program running output is the source program itself:
L8-2 L8-2.c C:/TC>
# I nclude <stdio. h>
Main (argc, argv)
Int argc;
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 a character from the file and display it to the screen */
Putchar (CH );
Fclose (FP );
}

[Example 8-3] input a token from the keyboard and save it to the test.txt file:
# I nclude <stdio. h>
Main ()
{
File FP;/* define the file variable pointer */
Char ch;
If (FP = fopen ("test.txt", "W") = NULL)/* open the file in write-only mode */
{
Printf ("cannot open file! /N ");
Exit (0 );
}
While (CH = fgetchar ())! = '/N')/* as long as the input character is not a carriage return */
Fputc (CH, FP)/* write a single character into the file */
Fclose (FP );
}
The program enters the designated stream file test.txt in a serial string from the keyboard. The file is opened in write-only mode, so the stream file is readable and can be accessed by various character processing tools. To put it simply, we can use the TYPE Command provided by DOS to list the file content.
Run the program:
I love China!
In the DOS operating system, the type command is used to display the test.txt file as follows:
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. Its function form is:
Char * fgets (char * STR, int num, file * Stream)
The fgets () function reads up to num-1 characters from the stream file and places them in the string array pointed to by Str. Read characters until you encounter a carriage return or e o f (File Terminator), or read the limited number of characters.
Int fputs (char * STR, file * Stream)
The fputs () function writes the string pointed to by STR to the stream file. When the operation is successful, the function returns 0, and the Failure Returns a non-zero value.

[Example 8-4] Write a string to the example and the example 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 a carriage return */
}
Fclose (FP);/* close the file */
}
Run the program and enter a string of no more than 1 2 7 characters from the keyboard to write the file. If the string length is 0, it is an empty string and the program ends.
Input: Hello!
How do you do
Good-bye!

After running, we use the dos type command list file:
C:/TC> type test.txt
Hello!
How do you do
Good-bye!
The empty string entered here is actually a separate carriage return because the gets function marks the end of the string as a carriage return.

[Example 8-5] Read a serial number from test1.txt, and then write a file test2.txt.
# I nclude <stdio. h>
# I nclude <string. h>
Main ()
{
File * FP1, * fp2;
Char STR [128];
If (FP1 = fopen ("test1.txt", "R") = NULL)
{/* Open File 1 in read-only mode */
Printf ("cannot open file/N ");
Exit (0 );
}
If (fp2 = fopen ("test2.txt", "W") = NULL)
{/* Open File 2 in write-only mode */
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 it to file 2 */
Printf ("% s", STR);/* display on screen */
}
Fclose (FP1 );
Fclose (fp2 );
}
The program operates on two files and defines two file variable pointers. Therefore, before operating the file, the two files should be opened at the same time (in no particular order) as needed. After reading and writing is completed, close the file. The design process is displayed on the screen at the same time as the file is written. Therefore, after the program runs, you should see that the same text file as the original file is added and the file content is displayed on the screen.

3. formatted read/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. Formatting and reading a file is to add the letter F to the front of the above function to become fscanf () and fprintf (). Function call method:
Int fscanf (File * stream, char * format, arg_list)
Int fprintf (File * stream, char * format, arg_list)
Stream is the stream file pointer, and the other two parameters are used exactly the same as scanf () and printf.

[Example 8-6] write some formatted data to a text file, and then read the displayed data from the file as a formatting Method to the screen.
The formatted data includes two student records, including the name, student ID, and score.
# I nclude <stdio. h>
Main ()
{
File * FP;
Int I;
Struct Stu {/* defines the struct type */
Char name [15];
Char num [6];
Float score [2];
} Student;/* indicates the struct variable */
If (FP = fopen ("test1.txt", "W") = NULL)
{/* Open the file by writing only the text */
Printf ("cannot open file ");
Exit (0 );
}
Printf ("input data:/N ");
For (I = 0; I <2; I ++)
{
Scanf ("% S % F", student. Name, student. Num, & Student. Score [0],
& Student. Score [1]);/* input from keyboard */
Fprintf (FP, "% S % 7.2f % 7.2f/N", student. Name, student. Num,
Student. Score [0], student. Score [1]);/* Write File */
}
Fclose (FP);/* close the file */
If (FP = fopen ("test.txt", "R") = NULL)
{/* Re-open the file in read-only mode */
Printf ("cannot open file ");
Exit (0 );
}
Printf ("output from file:/N ");
While (fscanf (FP, "% S % F/N", student. name, student. num, & student. score [0], student. score [1])! = EOF)
/* Read from file */
Printf ("% S % 7.2f % 7.2f/N", student. Name, student. Num,
Student. Score [0], student. Score [1]);/* display to screen */
Fclose (FP);/* close the file */
}
Program Design a file variable pointer, two open the same file in different ways, write and read formatted data, it is very important, that is, what format is used to write the file, the format must be used to read data from the file. Otherwise, the read data is inconsistent with the format controller, causing data errors. The preceding 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 content of the list file is displayed as follows:
C:/> type test.txt
Xiaowan j001 87.50 98.40
Xiaoli j002 99.50 89.60
The files accessed by this program can also be set as binary files. If the file is opened in the following way:
If (FP = fopen ("test1.txt", "WB") = NULL)
{/* Open the file in binary write-only mode */
Printf ("cannot open file ");
Exit (0 );
}
The results are the same.

4. Block-based read/write
The methods used to read and write files described earlier cannot write or read files in the form of complex data types. The C language provides block-based read/write methods for file operations, so that the array, struct, and Other types can be read and written at a time. The function for block-based file reading and writing is called as follows:
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) field from the stream file to which the stream points. Each field is of size (Field Length) characters long, and place them in the string array pointed to by B u F (buffer.
The fread () function returns the number of actually read fields. If the number of fields required to be read by the function call exceeds the number of fields stored in the file, an error occurs or has reached the end of the file. In actual operation, check carefully.
The fwrite () function writes the count (number of fields) field from the character array pointed to by the Buf (buffer zone) to the stream to which the stream points. Each field is of a length of characters, the number of fields written when the function operation is successful.
For block-based file read/write, files can only be created in binary file format when they are created.

[Example 8-7]: Write formatted data to the disk and read the data from the file to the screen.
# I nclude "stdio. H"
# I nclude "stdlib. H"
Main ()
{
File * FP1;
Int I;
Struct Stu {/* define struct */
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 % 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-write in binary to open the file 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 a file */
Printf ("% S % 7.2f % 7.2f/N", student. name, student. num, student. score [0], student. score [1]);/* display to screen */
}
Fclose (FP1 );
}
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
Generally, if the format of input data is complex, we can use data in various formats as 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 into integer, real, and long integers respectively. During use, write the header file math. h or stdlib. h In front of the program.

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/jiji262/archive/2007/10/21/1835971.aspx

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.