search
HomeBackend DevelopmentPHP TutorialPHP text operation method collection comparison

PHP text operation method collection comparison

Apr 04, 2018 am 10:43 AM
phpComparegather

The content of this article is a comparison of a collection of PHP text operation methods. Now I share it with everyone, and can also give a reference to friends in need

fgets and fputs, fread and fwrite, fscanf and fprintf

String reading and writing functions fgets and fputs

1. Reading string function The function of the fgets function is to read a string from the specified file into a character array. The function call is in the form: fgets( Character array name, n, file pointer); where n is a positive integer. Indicates that the string read from the file does not exceed n-1 characters. Add the end-of-string mark '\0' after the last character read. For example: fgets(str,n,fp); means to read n-1 characters from the file pointed to by fp and send them to the character array str.

[Example 10.4] Read a 10-character string from the e10_1.c file.

#include
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 definition A character array str with a total of 11 bytes is obtained. After opening the file e101.c as a text file, read 10 characters from it and send them to the str array. '\0' will be added to the last unit of the array, and then Display the output str array on the screen. The ten characters output are exactly the first ten characters of the program in Example 10.1.

There are two instructions for the fgets function:

1. Before reading n-1 characters, if a newline character or EOF is encountered, the reading ends.

2. The fgets function also has a return value, and its return value is the first address of the character array.

2. Write string function fputs

The function of fputs function is to write a string to the specified file. Its calling form is: fputs (string, file pointer) where string It can be a string constant, a character array name, or a pointer variable, for example:

fputs("abcd", fp);

The meaning is to write the string "abcd" into the file pointed to by fp. [Example 10.5] Append a string to the file string created in Example 10.2.

#include
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 adding a string to the end of the string file. Therefore, in line 6 of the program, append the read and write text file Open the file string. Then enter a string and use the fputs function to write the string to the file string. In line 15 of the program, use the rewind function to move the internal position pointer of the file to the beginning of the file. Then enter the loop to display all the contents of the current file one by one.


Data block reading and writing functions fread and fwrite

C language also provides reading and writing 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 structure variable, etc. The general form of a data block function call is: fread(buffer,size,count,fp); The general form of a data block function call is: fwrite(buffer,size,count,fp); where buffer is a pointer, in fread In the function, it represents the first address where the input data is stored. In the fwrite function, it represents the first address where the output data is stored. size represents the number of bytes in the data block. count represents the number of data blocks to be read and written. fp represents the file pointer.

For example:

fread(fa,4,5,fp); Its meaning is to read 4 bytes (a real number) each time from the file pointed to by fp and send it to the real number. In the array fa, read 5 times continuously, that is, read 5 real numbers into fa.

[Example 10.6] Enter two * from the keyboard, write it to a file, and then read the data of these two students and display it on the screen.

#include
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 ;iscanf("%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;iprintf("%s\t%5d% 7d%s\n",qq->name,qq->num,qq->age,qq->addr);
fclose(fp);
}

This example program defines a structure stu, indicating two structure arrays boya and boyb and two structure pointer variables pp and qq. pp points to boya, qq points to boyb. Line 16 of the program opens the binary file "stu_list" in read-write mode. After inputting two student data, write it into the file, then move the internal position pointer of the file to the beginning of the file, read out the two * blocks, and then display them on the screen. show.

Formatted read and write functions fscanf and fprintf

fscanf function, fprintf function has similar functions to the previously used scanf and printf functions. They are both formatted read and write functions. . The difference between the two is that the read and write objects of the fscanf function and the fprintf function are not the keyboard and monitor, but disk files. The calling format of these two functions is: fscanf (file pointer, format string, input table columns); fprintf (file pointer, format string, output table columns); For example:

fscanf(fp," %d%s",&i,s);
fprintf(fp,"%d%c",j,ch);

The problem in Example 10.6 can also be completed using the fscanf and fprintf functions. The modified program is shown in Example 10.7.

[Example 10.7]

#include
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;iscanf("%s%d%d%s",pp->name,&pp->num,&pp-> ;age,pp->addr);
pp=boya;
for(i=0;ifprintf(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;iprintf( "%s\t%5d %7d %s\n",qq->name,qq->num, qq->age,
qq->addr);
fclose(fp) ;
}

Compared with Example 10.6, the fscanf and fprintf functions in this program can only read and write one structure array element at a time, so a loop statement is used to read and write all array elements. Also note that the pointer variables pp and qq have changed their values ​​due to the loop, so they are reassigned the first address of the array in lines 25 and 32 of the program respectively.

Random reading and writing of files

The methods of reading and writing files introduced earlier are all sequential reading and writing, that is, reading and writing files can only start from the beginning and read and write each data sequentially. But in practical problems, it is often required to read and write only a specified part of the file. In order to solve this problem, you can move the position pointer inside the file to the location that needs to be read and written, and then read and write. This kind of reading and writing is called random reading and writing. The key to achieving random reading and writing is to move the position pointer as required, which is called file positioning. There are two main functions for file positioning to move the internal position pointer of a file, namely the rewind function and the fseek function.

The rewind function has been used many times before. Its calling form is: rewind (file pointer); Its function is to move the position pointer inside the file to the beginning of the file. The following mainly introduces the
fseek function.

The fseek function is used to move the internal position pointer of the file. Its calling form is: fseek (file pointer, displacement, starting point); where: the "file pointer" points to the moved file. "Displacement" represents the number of bytes moved, and the displacement is required to be long data so that no error occurs when the file length is greater than 64KB. When a constant is used to represent the displacement, the suffix "L" is required. "Starting point" indicates where to start calculating the displacement. There are three specified starting points: the beginning of the file, the current position and the end of the file.

The representation method is shown in Table 10.2.

Starting point                                                                                 tleken handdie
Current position SEEK—CUR 1
End of file SEEK—END 2

For example:

fseek(fp,100L,0); Its meaning is to move the position pointer away from The first 100 bytes of the file. It should also be noted that the fseek function is generally used for binary files. Due to the need for conversion in text files, errors often occur in calculated positions. After moving the position pointer, random reading and writing of files can be performed using any of the reading and writing functions introduced previously. Since a data block is generally read and written, the fread and fwrite functions are commonly used. The following examples are used to illustrate random reading and writing of files.

[Example 10.8] Read the second student’s data in the student file stu list.

#include
struct stu
{
char name[10];
int num;
int age;
char addr[15 ];
}boy,*qq;
main()
{
FILE *fp;
char ch;
int i=1;
qq=&boy;
if((fp=fopen("stu_list","rb"))==NULL)
{
printf("Cannot open file strike any key exit!");
getch();
exit(1);
}
rewind(fp);
fseek(fp,i*sizeof(struct stu),0);
fread(qq,sizeof(struct stu) ,1,fp);
printf("\n\nname\tnumber age addr\n");
printf("%s\t%5d %7d %s\n",qq->name ,qq->num,qq->age,
qq->addr);
}

The file stu_list has been created by the program in Example 10.6. This program uses randomly read Method reads the second student's data. In the program, boy is defined as a stu type variable, and qq is a pointer to boy. The file is opened for reading binary files, and line 22 of the program moves the file location pointer. The i value is 1, which means starting from the file header, moving the length of one stu type, and then reading the data is the second student's data.

File detection function

The commonly used file detection functions in C language include the following.

1. File end detection function feof function calling format: feof (file pointer);

Function: Determine whether the file is at the end of the file. If the file ends, the return value is 1, otherwise is 0.

2. Reading and writing file error detection function ferror function calling format: ferror (file pointer);

Function: Check whether there are errors when reading and writing files using various input and output functions. If the ferror return value is 0, it means there is no error, otherwise it means there is an error.

3. Set the file error flag and file end flag to 0 function clearerr function calling format: clearerr (file pointer);

Function: This function is used to clear the error flag and file end flag, so that They have a value of 0.

C library files

The C system provides a wealth of system files, called library files. C library files are divided into two categories, one is files with the extension ".h" , called a header file, we have used it many times in the previous include command. The ".h" file contains information such as constant definitions, type definitions, macro definitions, function prototypes, and various compilation selection settings. The other type is the function library, which includes the target code of various functions for users to call in the program. Usually when calling a library function in a program, the ".h" file where the prototype of the function is located must be included before the call.

All library functions are given in the appendix.

ALLOC.H   Describes memory management functions (allocation, release, etc.).
ASSERT.H   Definition assert debugging macro.
BIOS.H                      ​ Out over will call various functions of the IBM-PC ROM BIOS subroutine.
CONIO.H   Describes the various functions that call the DOS console I/O subroutine.
CTYPE.H Contains name type information about character classification and conversion (such as isalpha, toascii, etc.).
DIR.H   Contains structures, macro definitions and functions related to directories and paths.
DOS.H   Definition and description of some constants and functions called by MSDOS and 8086.
ERRON.H Defines the mnemonic for the error code.
FCNTL.H   Symbolic constants defined when connected to the open library subroutine.
FLOAT.H Contains some parameters and functions related to floating point operations.
GRAPHICS.H Describes various functions related to graphics functions, constant definitions of graphics error codes, various color values ​​​​for different drivers, and some special structures used by the functions.
IO.H   Contains the structure and description of low-level I/O subroutines.
LIMIT.H Contains information such as environmental parameters, compilation time limits, and number ranges.
MATH.H   Explains the mathematical operation function, also defines the HUGE VAL macro, and explains the special structure used by matherr and matherr subroutines.
MEM.H   Describes some memory operation functions (most of which are also described in STRING.H).
PROCESS.H Describes the various functions of process management, the structure description of spawn... and EXEC... functions.
SETJMP.H Define the jmp buf type used by the longjmp and setjmp functions, and describe these two functions.
SHARE.H Define the parameters of the file sharing function.
SIGNAL.H Define the SIG[ZZ(Z] [ZZ)]IGN and SIG[ZZ(Z] [ZZ)]DFL constants to illustrate the two functions rajse and signal.
STDARG.H Define the macro for reading the function parameter table. (Such as vprintf, vscarf functions).
STDDEF.H Define some public data types and macros.
STDIO.H Defines the standard and extended types and macros defined by Kernighan and Ritchie in Unix System V. Also defines standard I/O predefined streams: stdin, stdout and stderr, describing I/O stream subroutines.
STDLIB.H   Describes some commonly used subroutines: conversion subroutines, search/sort subroutines, etc.
STRING.H   Describes some string operation and memory operation functions.
SYS\STAT.H Defines some symbolic constants used when opening and creating files.
SYS\TYPES.H Describe the ftime function and timeb structure.
SYS\TIME.H Define the type of time time[ZZ(Z] [ZZ)]t.
TIME.H    Define the structure of the time conversion subroutines asctime, localtime and gmtime, the types used by ctime, difftime, gmtime, localtime and stime, and provide prototypes of these functions.
VALUE.H Defines some important constants, including those that depend on machine hardware and those specified for compatibility with Unix System V, including ranges of floating-point and double-precision values.

Related recommendations:

PHP text operation class_PHP tutorial

php text operation method collection comparison page 1/2_PHP Tutorial

The above is the detailed content of PHP text operation method collection comparison. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.