C language Read and write documents in the form of characters and sample code _c language

Source: Internet
Author: User

In C, read and write files are more flexible, can read and write one character at a time, can read and write a string, or even any byte of data (data block). This section describes reading and writing files in character form.

When you read and write a file as a character, you can read one character from the file at a time, or write a character to the file. The main uses are two functions: fgetc () and FPUTC ().

Character Read function fgetc

FGETC is the abbreviation for file get char, which means reading a character from the specified file. Its prototype is:

int fgetc (FILE *fp);

FP is a file pointer. FGETC () returns the character read when the read succeeds, or EOF when read to the end of the file or when the read fails.

EOF is the abbreviation for end of file, which indicates that a macro is defined in stdio.h, and that its value is a negative number, often-1. The return value type is int to accommodate this negative number (char cannot be a negative number).

EOF is not absolute-1, or it can be other negative numbers, which depends on the compiler's implementation.

FGETC () Use examples:

char ch;
FILE *FP = fopen ("D:\\demo.txt", "r+");
ch = fgetc (FP);

Represents reading a character from the D:\\demo.txt file and saving it to the variable ch.

There is a position pointer inside the file to point to the current read-write location, that is, read and write to the first few bytes. When a file is opened, the pointer always points to the first byte of the file. With the FGETC function, the pointer moves backwards one byte, so multiple characters can be read more than once using FGETC.

Note: The position pointer inside this file is not the same as the pointer in C language. A position pointer is simply a flag indicating where the file is read and written to, that is, reading to the first few bytes, which does not represent an address. Each time the file is read and written, the position pointer moves once, it does not require you to define and assign values in the program, but is automatically set by the system, transparent to the user.

The sample displays the contents of the D:\\demo.txt file on the screen.

#include <stdio.h>
int main () {
 FILE *fp;
 char ch;
 
 If the file does not exist, give the prompt and exit if (
 (Fp=fopen ("D:\\demo.txt", "rt") = = NULL) {
  printf ("Cannot open file, press any key to exit! ");
  Getch ();
  Exit (1);
 }
 Reads one byte at a time until it finishes reading while
 ((CH=FGETC (FP)!= EOF) {
  putchar (ch);
 }
 Putchar (' \ n '); Output line newline character
 fclose (FP);
 return 0;
}

Create a Demo.txt file under D disk, enter any content and save, run the program, you will see just entered the content is displayed on the screen.

The function of the program is to read the characters from the file and display them on the screen until the read is complete.

The 14th line of the program is critical, while the condition for The loop is (CH=FGETC (FP))!= EOF. Fget () reads one character at a time from the position pointer, and saves it to the variable ch, where the position pointer moves one byte backward. When the file pointer moves to the end of the file, Fget () cannot read the character, and then returns EOF, indicating that the file read is finished.

Description of EOF

EOF originally represents the end of the file, which means that the read ended, but many functions return EOF when the error is read, so when EOF is returned, is the file read or read wrong? We can use the two functions in stdio.h to judge, respectively, feof () and ferror ().

The feof () function is used to determine whether the file's internal pointer points to the end of the file, and its prototype is:

int feof (FILE * fp);

Returns a value other than 0 when pointing at the end of the file, or 0.

The Ferror () function is used to determine whether a file operation is wrong, and its prototype is:

int ferror (FILE *fp);

Returns a value other than 0 when an error occurs, otherwise it returns a value of 0.

It is important to note that file errors are rare cases where the above example guarantees that the data in the file is read. If you pursue perfection, you can also add judgment and give a hint:

#include <stdio.h>
int main () {
 FILE *fp;
 char ch;
 
 If the file does not exist, give the prompt and exit if (
 (Fp=fopen ("D:\\demo.txt", "rt") = = NULL) {
  printf ("Cannot open file, press any key to exit! ");
  Getch ();
  Exit (1);
 }
 Reads one byte at a time until it finishes reading while
 ((CH=FGETC (FP)!= EOF) {
  putchar (ch);
 }
 Putchar (' \ n '); Output newline character
 if (ferror (FP)) {
  puts (read error);
 } else{
  puts ("read succeeded");
 }
 Fclose (FP);
 return 0;
}

In this way, whether it is a mistake or normal reading, you can do a good idea.

Character Write function Fputc

FPUTC is file output char, so it means writing a character to the specified file. The call is in the form of:

int FPUTC (int ch, FILE *FP);

Ch for the character to be written, FP is the file pointer. FPUTC () returns the written character when the write succeeds, and EOF when it fails, and the return value type is int to accommodate the negative number. For example:

FPUTC (' A ', FP);

Or:

char ch = ' a ';
FPUTC (CH, FP);

Indicates that the character ' A ' is written to the file that the FP points to.

Two point description

1 The written file can be opened by writing, reading and writing, appending, and writing or read-write to open an existing file will clear the original file content, and put the written characters at the beginning of the file. You must open the file as an append if you want to keep the original file content and place the characters written at the end of the file. Regardless of how it is opened, the file being written is created if it does not exist.

2 each write one character, the file internal position pointer moves backward one byte.

The example enters a line of characters from the keyboard and writes to the file.

#include <stdio.h>
int main () {
 FILE *fp;
 char ch;
 Determine if the file successfully opened
 if ((Fp=fopen ("D:\\demo.txt", "wt+") = = NULL) {
  printf ("Cannot open file, press any key to exit!\n") ;
  Getch ();
  Exit (1);
 }
 printf ("Input a string:\n");
 Reads one character at a time from the keyboard and writes to the file while
 ((Ch=getchar ())!= ' \ n ') {
  fputc (CH,FP);
 }
 Fclose (FP);
 return 0;
}

Run the program, enter a line of characters and press ENTER to finish, open the Demo.txt file under D disk, you can see what you just entered.

The program reads one character at a time from the keyboard and writes to the file until the ENTER key is pressed and the while condition does not set, ending the read.

The above is the C language to read and write documents in the form of basic information, follow-up continue to add relevant information, thank you for your support of this site!

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.