Count the number of characters in the file and the number of characters in the file

Source: Internet
Author: User
Tags rewind

Count the number of characters in the file and the number of characters in the file

The so-called "file" refers to an ordered set of related data. This dataset has a name
It is called a file name. Files usually reside on external media and are called only when used.
In memory.

There are many classification methods for file classification. Here we will look at the file encoding method.
Based on the file encoding method, files can be divided into ASCII and binary files.
An ASCII file is also called a text file. Each character corresponds to
Bytes, used to store the corresponding ASCII code. For example, the storage format of the number 5678 is:
ASCII code: 00110101 00110110 00110111 00111000
Decimal: 5 6 7 8
It occupies 4 bytes in total. ASCII code files can be displayed by characters on the screen.

Binary files are stored in binary encoding. For example
The storage format is 00010110 00101110, which only occupies two bytes. Although the binary file can be displayed on the screen, its content cannot be understood. When processing these files in C language, the types are not differentiated. They are regarded as byte streams and processed in bytes.

The file Pointer Points to a file using a pointer variable in C language. This pointer is called a file pointer. The file pointer can be used to perform various operations on the file. The definition FILE pointer is generally a "FILE" pointer variable identifier. The FILE should be capitalized. It is actually a structure defined by the system, which contains information such as the FILE name, FILE status, and current position. When writing a source program, you do not have to worry about the details of the FILE structure. For example, "FILE fp" indicates that fp is a pointer variable pointing to the FILE structure. Through fp, you can find the structure variable that stores the information of a FILE, and then find the FILE according to the information provided by the structure variable, perform operations on files.

In C, file operations are performed by library functions. File Operations include opening, reading, writing, and closing.

1: fopen function

The fopen function is used to open a file. The Calling method is generally as follows:
File pointer name = fopen (file name, file method)
The "FILE pointer name" must be described as a FILE-type pointer variable. The "FILE name" is the FILE name of the opened FILE.
"File Usage" refers to the file type and operation requirements. The "file name" is a String constant or a string array.
For example:
FILE fp;
Fp = fopen ("file. a", "r ");
// It means to open file. a in the current directory, only allow "read" operations, and make fp point to the file
There are 12 file methods.

The usage of files is described as follows:

The usage of a file is composed of 6 characters, namely r, w, a, t, B, and +. The meaning of each character is r (read) read, w (write) write,
Append a (append), t (text) text file, can be omitted without writing; B (binary) binary file; "+" read and write
When opening a file with r, the file must already exist and can only be read from the file
A file opened with w can only be written to the file. If the opened file does not exist, it is created with the specified file name.
This file. If the opened file already exists, delete the file and create a new file.
To append new information to an existing file, you can only open the file in method. However, the file must be
Otherwise, an error occurs.

If an error occurs when opening a file, fopen returns a NULL pointer value. In the program, you can
Use this information to determine whether the file is opened and process the file accordingly. For example:

If (fp = fopen ("file. a", "rb") = NULL)
{
Printf ("\ nerror no open file. !");
Getch ();
Exit (1 );
}

2: Close the file

The call is generally in the following format:
Fclose (File pointer );
When the file close operation is completed normally, the fclose function returns 0. If the non-zero value is returned, an error occurs.

3: file read/write Functions

Many file read/write functions are provided in C language. Character read/write functions fgetc and fputc; string read/write functions fgets and
Fputs; data block read/write functions fread and fwrite; format read/write functions fscanf and fprintf; these functions
Are included in the stdio. h header file.

(1): read character function fgetc

The fgetc function reads a character from a specified file. The function is called in the following form:
Character variable = fgetc (File pointer );
Note that the file pointer and the position pointer inside the file are different. The file Pointer Points to the entire file,
It needs to be defined in the program. As long as no value is assigned again, the value of the file pointer remains unchanged. File
The position pointer is used to indicate the current read/write position inside the file. Each read/write operation moves the pointer backward,
It does not need to be defined in the program, but is automatically set by the system.

(2): Write the character function fputc

The fputc function writes a character to a specified file. The function is called in the following form:
Fputc (character, file pointer );
The fputc function has a return value. If the write is successful, the written characters are returned. Otherwise, the EOF

(3): String read/write functions fgets and fputs

The fgets function reads a string from a specified file to a character array,
The function is called in the following format:
Fgets (character array name, n, file pointer );
N is a positive integer, indicating that the string read from the file cannot exceed n-1 characters.
Add the end string '\ 0' to a character '. The fgets function has two points: Before reading n-1 characters, if
If a line break or EOF is encountered, the operation is terminated. The fgets function also has a return value, which is the first character array.
Address.
Call Method for writing string functions:
Fputs (string, file pointer );

(4): block data read/write functions fread and fwrite

Call form:
Fread (buffer, size, count, fp );
Fwrite (buffer, size, count, fp );
Buffer is a pointer. In fread, it indicates the first address to store the input data. In fwrite,
It indicates the first address to store the output data. Size indicates the number of bytes of the data block, and count indicates
The number of data blocks.

(5) Formatting read/write functions fcanf and fprintf

Call form:
Fcanf (File pointer, Format String, input table column );
Fprintf (File pointer, Format String, output table column );

The following are the requirements for this instance:

Compile a program for counting the characters in a file. It mainly learns the concepts and operations of the file.

The following is my code implementation:

# Include <stdio. h> # include <stdlib. h>/*** program for compiling the number of characters in a statistical file, mainly learning about file concepts * and file operations. */Int main () {/** number of characters saved **/int count = 0;/** save file name **/char fname [80]; /** FILE pointer **/file * fp; printf ("Please enter the FILE name:"); scanf ("% s", fname ); if (fp = fopen (fname, "r") = NULL) {printf ("Open file failed !! \ N "); exit (1);} count = 0; while (fgetc (fp )! = EOF) count ++; fclose (fp); printf ("There are % d characters in file % s. \ n", count, fname); return 0 ;}

The following is my test example (test.txt ):

cnuidocncn  cwncviow wedcvnwicvmnw dcvnwidcvn cvwiovm  wvcewoivm wevcovw vcmweiocvmwmvciomvw nvi] vwevmovjovwvjkvnivpvmwvciwmvw'nvoikvvnvwvmjeewevvvvwvwkvnpowiehf]ewnveiowv

Now, let's take a look at my running process:

In addition, we can perform random read/write operations on files. Some file locating functions are provided in C. We usually use two functions: rewind and fseek.

The two functions are called in the following forms:

Rewind (File pointer ).

Its function is to move the position pointer inside the file to the beginning of the file.

Fseek (File pointer, displacement, starting point );

Move the internal position pointer of the file to the desired position.

Copyright Disclaimer: Hello, please leave the address of your blog for reprinting. Thank you.

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.