“This is the 13th day of my participation in the August Text Challenge.

The standard IO

Definition of standard IO

Standard IO is an API interface provided by the standard C library. It is a function interface encapsulated on the basis of file IO.

πŸ“Œ The first reason is to increase portability. Also, standard IO encapsulates something called a buffer on top of file IO. Improve kernel efficiency. Used to store some data that is not very urgent, wait until the buffer is full, call a file IO to complete the writing or reading work.

Some data is particularly urgent data such as: command delivery, real-time monitoring data must use file IO.

Pseudocode: fopen (argument) {if(is win) {_open(argument); }esle if (is Linux) {open(parameter); }}

File stream pointer

File stream pointer: a file flag, a structure pointer wrapped around the file descriptor, in which the buffer resides.

Stream: stream pointer —- file stream pointer — this stream

After the code

Install an indexed search file tags

Ctags -r // Generate an engine FILE called tags, which contains information about the directory. Step 2: Search for vi-t + target string for example: vi-t FILE Step 3: Step 4: Browse through the document -- code jump after code: click the string you want to jump to, CTRL +] enter jump search returns last time: CTRL + TCopy the code

​

Set global Tags

The vim configuration file for the editor directory **. Vimrc ** adds tags to the end as follows:

set tags+=/user/include/tags

Standard IO function interface

1.fopen

  1. FILE *fopen(const char *pathname, const char *mode);

  2. Open a file

  3. Parameters:

    Pathname: indicates the path and name of the file to be opened

    Mode: mode of opening a file

    The specific explanation open() flag
    r To open a file in read-only mode, the file must exist O_RDONLY
    r+ To open the file in read-write mode, the file must exist O_RDWR
    w The write is cleared if the file exists, and the write is created if the file does not exist O_WRONLY|O_CREAT|O_TRUNC
    w+ Clear the read and write if the file exists, create the read and write if the file does not exist O_RDWR|O_CREAT|O_TRUNC
    a If the file exists, it is appended. If the file does not exist, it is created before writing O_WEONLY|O_CREAT|O_APPEND
    a+ If the file does not exist, the file is created and appending writes and reads. Read from the beginning of the file, write from the end of the file after the lSEEK offset cannot be written, if the write operation is entered, the append is written to the end (regardless of the offset before the write) O_RDWR|O_CREAT|O_APPEND

    Note: It is possible to encounter rb+ in the future, where b stands for performing binary operations

  4. The return value:

    Success returns a stream pointer to the file

    Return NULL on failure

  5. Code:

#include <stdio.h>
int main(int argc, const char *argv[])
{
    // To open a file, you need to define a file stream pointer to point to the encapsulated file stream pointer returned by fopen
    //FILE * fp = fopen("./1.txt","r");
    FILE * fp = fopen("./1.txt"."w");
    if (NULL == fp)
    {
        perror("fopen");
        return - 1;
    }
    printf("Opening file was successful \n");
    return 0;
}
Copy the code

​

2.fclose

  1. Prototype: int fclose(FILE *stream);

  2. Function: Close a file stream pointer // Cause: A file stream pointer is bound to a file descriptor

  3. Parameter: target file stream pointer

  4. The return value:

    Returns 0 on success

    Failure returns: EOF == -1

3.fgetc

  1. Prototype: int fgetc(FILE *stream);

  2. Returns a character from the specified file stream pointer

  3. Parameter: target stream pointer

  4. The return value:

    Successfully returns the data converted to int from the retrieved character

    Failure to return EOF to end of file EOF

πŸ“’ Note: after obtaining, the pointer moves one bit

int buf = fgetc(fp);         
printf("%c\n",buf);
printf("%d\n".sizeof(buf));

linux@ubuntu:~/test/IO/test$ ./a.out 
h
4
Copy the code

4.feof

  1. Prototype: NT feof(FILE *stream);

  2. Function: Determine whether the end of the file has been reached

  3. Parameter: target file stream pointer

  4. The return value:

    Returns a non-zero value if the end of the file is reached

    Otherwise 0 is returned

5.ferror

  1. Prototype: int ferror(FILE *stream);

  2. Function: Check whether the file operation is wrong

  3. Parameter: target file stream pointer

  4. The return value:

    If the file operation fails, return a non-zero value

    Otherwise 0 is returned

  5. Code:

#include <stdio.h>
int main(int argc, const char *argv[])
{
    // Open a file in r+ mode
    FILE * fp = fopen("./1.txt"."r");
    if (NULL == fp)
    {
        perror("fopen");
        return - 1;
    }
    
    // Start reading the loop
    while(1)
    {
        int ret = fgetc(fp);
        if (EOF == ret)
        {
            // The end of the file was reached or the function failed
            if (feof(fp))
            {
                printf("Reached the end of file \n");
                break;
            }else{
                printf("Fetch failed \n"); \return - 1; }}printf("The data obtained is %d-- the corresponding character is %c\n",ret,ret);

    }
    if( fclose(fp) == EOF)
    {
        printf("Failed to close file \n");
        return - 1;
    }
    return 0;
}
Copy the code

​

linux@ubuntu:~/test/IO/test$./a.out The obtained data is104-- The corresponding character is h. The obtained data is101-- The corresponding character is e. The obtained data is108-- The corresponding character is L. The obtained data is108-- The corresponding character is L. The obtained data is111-- The corresponding character is o. The obtained data is32-- The corresponding character is the obtained data is119-- The corresponding character is w. The obtained data is111-- The corresponding character is o. The obtained data is114-- The corresponding character is r108-- The corresponding character is L. The obtained data is100-- The corresponding character is d10-- The corresponding character is/ / vim '\ n'The end of the file is reachedCopy the code

​

6.fputc

  1. Prototype: int fputc(int c, FILE *stream);

  2. Function: Outputs a character to a specified file

  3. Parameters:

    C: unsignedchar (int, unsignedchar

    β‘‘ stream: indicates the target file stream pointer

  4. The return value:

    Return on success: the written character is converted to int

    Return on failure: EOF

  5. Code:

#include <stdio.h>

int main(int argc, const char *argv[])
{
    // Open the file
    FILE * fp = fopen("./1.txt"."w");
    if (NULL == fp)
    {
        perror("fopen");
        return - 1;
    }
    // Start writing data to the file
    char buf[123] = "hello world";
    int i = 0;
    while(1)
    {
        fputc(buf[i],fp);
        if ((strlen(buf) - 1 ) == i)
        {
            break;
        }       
        i++;// Iterate over the number group
    }
    fclose(fp);
    return 0;
}
Copy the code

​

Exercise: Copy and paste files using fgeTC and fpuTC

7.fgets

  1. Char *fgets(char *s, int size, FILE *stream);

  2. Function: Line read

  3. Parameters:

    β‘  S: the address where the read data is stored

    β‘‘ size: number of bytes read

    1. When the number of bytes before \n is less than size, a newline character is encountered, but the newline character is also read into memory as a character, and ‘\0’ is appended after the last character.

    2. If the number of bytes before \n is larger than size, the read will stop when the number of bytes before \n is larger than size. A ‘\0’ will be added to the end. Will overwrite the character of the last byte. The mechanism shifts the read/write pointer forward by one byte after reading.

    β‘’stream: indicates the file stream pointer

  4. The return value:

    Return on success: the first address of the string read

    Returns NULL on failure

    Read to end of file: Returns NULL

  5. Code:

#include <stdio.h>
int main(int argc, const char *argv[])
{
    FILE * fp = fopen("./1.txt"."r");
    if (NULL ==fp)
    {
        perror("fopen");
        return - 1;
    }
    / / read
    while(1)
    {
    char buf[123] = {0};
    if (fgets(buf,11,fp) == NULL)
    {   
        // Failed or read the end of the file
        if (feof(fp))
        {
            printf("Read the end of the file \n");
            break;
        }else{
            perror("fgets");
            return - 1; }}printf("buf = %s\n",buf);
    }
    return 0;
}
Copy the code

​

if (fgets(buf,11,fp) == NULL)
linux@ubuntu:~/test/IO/test$ ./a.out 
buf = hello worl	//hello worl'\0' //'\0' overwrites d, but the mechanism protects d from loss
buf = d			   //d'\n''\0'Read to the end of the fileif (fgets(buf,12,fp) == NULL)
linux@ubuntu:~/test/IO/test$ ./a.out 
buf = hello world	//hello world'\0'
buf = 			   //'\n''\0'Read to the end of the fileif (fgets(buf,13,fp) == NULLlinux@ubuntu:~/test/IO/test$./a.out buf = hello world,//hello world'\n''\0'Read to the end of the fileCopy the code

8.fputs

  1. Function: Input a string to a file

  2. Prototype: int fputs(const char *s, FILE *stream);

    πŸ“’ Note: stop when ‘\0’ is encountered

  3. Parameters:

    β‘  S: address of the data to be written

    β‘‘ stream: Which file you want to write to

  4. The return value:

    Success returns a non-negative number

    Failure returns EOF (-1)

  5. Code:

#include <stdio.h>
int main(int argc, const char *argv[])
{
    FILE * fp = fopen("./1.txt"."w");
    if (NULL ==fp)
    {
        perror("fopen");
        return - 1;
    }
    // Find the address of the data you want to write to
    char buf[123] = "hello world";

    if (EOF == fputs(buf,fp))
    {
        perror("fputs");
        return - 1;
    }
    return 0;
}
Copy the code

​

πŸ“ exercise: Write a code that tests the number of lines in a file.

Code:

#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
    if(argc ! =2)
    {
        printf("Parameter input error \n");
        return - 1;
    }
    // Open the file in read-only mode
    FILE * fp = fopen(argv[1]."r");
    if (NULL == fp)
    {
        perror("fopen");
        return - 1;
    }
    // Start counting
    int count = 0;// For counting purposes
    while(1)
    {
        char buf[123] = {0};
        if (NULL == fgets(buf,sizeof(buf),fp))
        {
            // Error or end of file
            if (feof(fp))
            {
                printf("Reached the end of file \n");
                break;
            }else{
                perror("fgets");
                return - 1; }}if (buf[strlen(buf) - 1] = ='\n') { count++; }}printf("The file line number is %d\n",count);

    return 0;
}
Copy the code

​

linux@ubuntu:~/test/IO/test$ ./a.out 1.TXT reaches the end of the file and the number of lines in the file is0

linux@ubuntu:~/test/IO/test$ vi 1.txt 
// Here I go into the vim editor and then delete the file, the number of lines will be 1

linux@ubuntu:~/test/IO/test$ ./a.out 1.TXT reaches the end of the file and the number of lines in the file is1
Copy the code

9.fread

  1. Fread (void * PTR, size_t size, size_t nmemb, FILE *stream);

  2. Function: binary read file

  3. Parameters:

    β‘  PTR: address for storing read data

    β‘‘ size: indicates the size of the object

    β‘’ nmemb: number of objects πŸ“’ Note: The total number of bytes read is the size of the object x the number of objects

    β‘£ stream: indicates the target file stream pointer

  4. The return value:

    Successfully returns the number of read objects

    Failure returns a 0

10.fwrite

  1. Prototype: size_t fwrite(const void * PTR, size_t size, size_t nmemb, FILE *stream);

  2. Function: binary write file

  3. Parameters:

    β‘  PTR: the first address of the data to be written

    β‘‘ size: indicates the size of the object

    β‘’ NMEMB: indicates the number of objects

    β‘£ stream: indicates the target file stream pointer

  4. The return value:

    Successfully returns the size of the object being written

    Failure returns a small number of objects

  5. Code:

#include <stdio.h>
#include <string.h>
// Define an information structure
struct age
{
    char name[20];
    char sex;
    int age;
    char phone[12];
};
struct age myage1;// Define a structure to use when typing
struct age myage2;// Define a structure to use when reading
int main(int argc, const char *argv[])
{
STAT:
    // Build the interface
    printf("************************************\n");
    printf("**1. Input information ****2. Read information *****3. Exit **\n");
    printf("************************************\n");
    // The user starts typing commands
    printf("input >> ");
    int input = 0;
    scanf("%d",&input);
    if(input >3 || input <= 0)
    {
        goto STAT;
    }
    // Start writing
    if (1 == input)
    {
        // Input information
        printf("Please enter name \n");
        scanf("%s",myage1.name);
        getchar();
        printf("Please enter gender \n");
        scanf("%c",&myage1.sex);
        getchar();
        printf("Please enter age \n");
        scanf("%d",&myage1.age);
        
        printf("Please enter your mobile phone number \n");
        scanf("%s",myage1.phone);
        getchar();

 // Start writing to the file -------------------------------
        FILE *fp = fopen("./.1.txt"."a");
            if (NULL == fp)
            {
                perror("fopen");
                return - 1;
            }
        // Start writing
        if(1! = fwrite(&myage1,sizeof(myage1),1,fp))
        {
                perror("fwrite");
                return - 1;
        }
        fclose(fp);
        printf("Writing message completed, jumping to menu \n");
        goto STAT;
    }else if (2 == input)
    {
        char username[23] = {0};
        // Read the information
        printf("Please enter the name of the person you want to inquire \n");
        scanf("%s",username);
        getchar();
        // Start reading and matching files
         FILE *fp = fopen("./.1.txt"."r");
        if (NULL == fp)
        {
            perror("fopen");
            return - 1;
        }
        while(1)// loop read
        {
                if(0 == fread(&myage2,sizeof(myage2),1,fp))
                {
                    if (feof(fp))
                    {
                        printf("Read the end of the file \n");
                        break;
                    }else{
                        perror("fread");
                        return - 1; }}// Match the name
                if (strcmp(username,myage2.name) == 0 )
                {
                  printf("Name %s\n",myage2.name);
                  printf("Sex %c\n",myage2.sex);
                  printf("Age %d\n",myage2.age);
                  printf("Mobile phone number: %s\n",myage2.phone); }}}else {

        / / exit
        return 0;
    } 
    return 0;
}
Copy the code

​


11.fseek

  1. Int fseek(FILE *stream, long offset, int whence);

  2. Function: Read/write pointer offset

  3. Parameters:

    β‘  stream: pointer to the destination file stream

    (2) offset:

    The number is negative and is offset forward. If the offset is out of the beginning of the file, an error is returned if

    The number is positive and is offset backwards. If it is offset out of the end of the file, the file is enlarged and filled with ‘\0’. Such files are called empty files

    πŸ“’ Note: If no write is done to the offset, the kernel considers the offset invalid and does not increase the file size.

    β‘’ whence: The baseline position —– is offset according to which position

    SEEK_SET(0): offset based on the start of the file

SEEK_CUR(1): indicates the offset based on the current position of the user. SEEK_END(2): indicates the offset based on the end of the file

  1. The return value:

    Returns 0 on success

    Returns -1 on failure

  2. Code:

#include <stdio.h>

char ch = 0;

int main(int argc, const char *argv[])
{
    // Open a file
    FILE *fp = fopen("./1.txt"."r+");
    if (NULL ==fp)
    {
        perror("fopen");
        return - 1;
    }

    // The data in the file is Hello World

    // Offset back from the end -- empty file
    fseek(fp,2000,SEEK_END);

    fputc('a',fp);
#if 0
    // Start pointer offset
    ch = fgetc(fp);
    printf("ch = %c \n",ch);
    fseek(fp,1,SEEK_CUR);// Offset one byte back from the current position
    ch = fgetc(fp);
    printf("ch = %c \n",ch);//--->l

    fseek(fp,- 1 ,SEEK_END);

    ch = fgetc(fp);
    printf("ch = %c \n",ch);//--->d
#endif
    return 0;
}    
Copy the code

Such as:

1. TXT file

πŸ“’ Note: d is not the end of the file, ‘\n’ is

fseek(fp,1,SEEK_SET);// Offset one byte back from the start of the file
ch = fgetc(fp);
printf("ch = %c \n",ch);
linux@ubuntu:~/test/IO/fseek$ ./a.out 
ch = e 

fseek(fp,10,SEEK_SET);
linux@ubuntu:~/test/IO/fseek$ ./a.out 
ch = d

fseek(fp,11,SEEK_SET);
linux@ubuntu:~/test/IO/fseek$ ./a.out 
ch = 
         //πŸ“’ Note the empty line because the vim editor automatically adds a '\n'

fseek(fp,12,SEEK_SET); linux@ubuntu:~/test/IO/fseek$./ a.otch = οΏ½ fseek(fp,13,SEEK_SET); linux@ubuntu:~/test/IO/fseek$./a.out = οΏ½Copy the code
fseek(fp,1,SEEK_CUR);// Offset one byte back from the current position
ch = fgetc(fp);
printf("ch = %c \n",ch);
linux@ubuntu:~/test/IO/fseek$ ./a.out 
ch = e 
Copy the code
fseek(fp,0 ,SEEK_END);
ch = fgetc(fp);
printf("ch = %c \n",ch); linux@ubuntu:~/test/IO/fseek$./ a.otch = οΏ½ fseek(fp,- 1 ,SEEK_END);
ch = fgetc(fp);
printf("ch = %c \n",ch);
linux@ubuntu:~/test/IO/fseek$ ./a.out 
ch = 

fseek(fp,2 - ,SEEK_END);
ch = fgetc(fp);
printf("ch = %c \n",ch);
linux@ubuntu:~/test/IO/fseek$ ./a.out 
ch = d 
Copy the code

​


12.ftell

  1. Prototype: Long ftell(FILE *stream);

  2. Run the following command to obtain the offset of the current read/write pointer

  3. Parameter: target file stream pointer

  4. The return value:

    Successfully returned offset (calculated from the beginning of the file)

    Returns -1 on failure

  5. Usage scenario: Usually used in conjunction with fseek(FP,0,SEEK_END) to measure the current size of the file

  6. Code:

#include <stdio.h>

int main(int argc, const char *argv[])
{
    FILE *fp = fopen("./1.txt"."r+");
    if (NULL ==fp)
    {
        perror("fopen");
        return - 1;
    }
    // Offset back from the end -- empty file
    fseek(fp,2000,SEEK_END);
    printf("Current offset is %ld\n",ftell(fp));
    fputc('a',fp);
    printf("Current offset is %ld\n",ftell(fp));
    return 0;
}
Copy the code
linux@ubuntu:~/test/IO/test$./a.out The offset is2006The current offset is2007linux@ubuntu:~/test/IO/test$./a.out The offset is4007The current offset is4008linux@ubuntu:~/test/IO/test$./a.out The offset is6008The current offset is6009
Copy the code

13.rewind

  1. Void rewind(FILE *stream);
  2. Fseek (stream, 0L, SEEK_SET) fseek(stream, 0L, SEEK_SET)
  3. Parameter: target file stream pointer
  4. Returned value: None
  5. Code:
rewind(fp); 
printf("Current offset is %ld\n",ftell(fp));        
Copy the code

14.sprintf

  1. Int sprintf(char * STR, const char *format,…) ;

  2. Function: Store a string to a fixed address (generally used for string concatenation)

  3. Parameters:

    β‘  STR: the address to store the formatted string

    β‘‘ format: format string {fixed string and placeholder}

    (3)… : variable parameters (generally placed variables)

  4. Return value: Number of bytes output on success negative on failure

  5. Code:

#include <stdio.h>
int main(int argc, const char *argv[])
{
    //name age sex phone
    char name[20] ="zhangsan";
    int age = 18;
    char sex = 'w';
    char phone[12] = "12345678922";
    char buf[123] = {0};
    // Start splicing
    sprintf(buf,"name:%s--age:%d--sex:%c--phone:%s",name,age,sex,phone);
    printf("buf = %s \n",buf);
    return 0;
}
Copy the code
linux@ubuntu:~/test/IO/test$ ./a.out 
buf = name:zhangsan--age:18--sex:w--phone:12345678922 
Copy the code

15.snprintf

  1. Int snprintf(char * STR, size_t size, const char *format,…) ;

  2. Function: output a formatted string to a character address at a fixed size

  3. Parameters:

    < span style = “font-size: 14px; color: RGB (50, 50, 50);

    β‘‘ STR: the address to store the formatted string

    β‘’ Format: format string {fixed string and placeholder}

    (4)… : variable parameters (generally placed variables)

  4. The return value:

    Success returns: Returns the total size of the target string

    Return on failure: negative

16.fprintf

  1. Int fprintf(FILE *stream, const char *format,…) ;

  2. Function: Format the output string into a file (generally used for writing log files)

  3. Parameters:

    β‘  stream: pointer to the destination file stream

    β‘‘ STR: the address to store the formatted string

    β‘’ Format: format string {fixed string and placeholder}

    (4)… : variable parameters (generally placed variables)

  4. The return value:

    Success return: Returns the size of the output in bytes

    Return on failure: negative

  5. Code:

#include <stdio.h>
int main(int argc, const char *argv[])
{
    //name age sex phone
    char name[20] ="zhangsan";
    int age = 18;
    char sex = 'w';
    char phone[12] = "12345678922";
    // Open the file
    FILE * fp = fopen("./1.txt"."w");
    if(NULL == fp)
    {
        perror("fopen");
        return - 1;
    }
fprintf(fp,"name:%s--age:%d--sex:%c--phone:%s",name,age,sex,phone);
    return 0;
}
Copy the code

Write a simple log file

#include <stdio.h>
#include <time.h>
int main(int argc, const char *argv[])
{
    // Open a file
    FILE *fp = fopen("./1.txt"."a");
    if(NULL == fp)
    {
        perror("fopen");
        
        return - 1;
    }
    while(1)
    {
        // Get the current distance from 1970 in seconds
        time_t mytime = time(NULL);
        // Start converting time
        struct tm * mytm = localtime(&mytime);
        fprintf(fp,"The current time is :%d year -%d month -%d day --%d:%d:%d\n",
        mytm->tm_year+1900,mytm->tm_mon+1,mytm->tm_mday,
        mytm->tm_hour,mytm->tm_min,mytm->tm_sec);
        fflush(fp);
        sleep(1);
    }
    return 0;
}
Copy the code

tail -f 1.txt

linux@ubuntu:~/test/test$tail -f 1.txt The current time is: 2021-August-25 --15:47:5 The current time is: 2021-August-25 --15:47:6 The current time is: 2021-August 25 --15:47:7 The current time is: 2021-August 25 --15:47:8 the current time is: 2021-August 25 --15:47:9Copy the code