Standard IO_File reading and writing_fgetc,getchar,ungetc,fgets,fputs,fread,fwrite

Table of contents

1. Single character file reading and writing

1.1 Single character reading file

1.1.1 fgetc function

1.1.2 getc function

1.1.3 getchar function

1.1.4 ungetc function

1.1.5 Comprehensive example code for single-character file reading

1.2 Single character writing file

1.2.1 fputc function

1.2.2 putc function

1.2.3 putchar function

1.2.4 Comprehensive sample code for single-character file writing

2. Multi-character file reading and writing

2.1 Multi-character reading file

2.1.1 fgets function

2.1.2 gets function

2.1.3 Comprehensive sample code for reading multi-character files

2.2 Writing files with multiple characters

2.2.1 fputs function

2.2.2 puts function

2.2.3 Comprehensive sample code for writing multi-character files

3. Binary reading and writing

3.1 Binary file reading

3.1.1 fread function

3.1.2 fread function sample code

3.2 Binary writing file

3.2.1 fwrite function

3.2.2 fwrite function sample code


1. Single character file reading and writing

1.1 Single character reading file

1.1.1 fgetc function

#include <stdio.h>

int fgetc(FILE *stream);

Function introduction: The fgetc function is one of the functions in C language used to read data character by character from a file.

Function parameters:

stream: The file pointer to be read.

Function return value:

Success: Returns the characters read as an integer.

Failure: If the reading fails or the end of the file is reached, EOF (End of File) is returned.

1.1.2 getc function

#include <stdio.h>

int getc(FILE *stream);

Function introduction: The getc function is one of the functions in C language used to read data character by character from a file.

Function parameters:

stream: The file pointer to be read.

Function return value:

Success: Returns the characters read as an integer.

Failure: If the reading fails or the end of the file is reached, EOF (End of File) is returned.

1.1.3 getchar function

#include <stdio.h>

int getchar(void);

Function introduction: The getchar function is a standard library function in C language, used to read a character from the standard input stream (stdin).

Function parameters:

No parameters.

Function return value:

Success: Returns the characters read as an integer.

Failure: If the reading fails or the end of the file is reached, EOF (End of File) is returned.

1.1.4 ungetc function

#include <stdio.h>

int ungetc(int c, FILE *stream);

Function introduction: The ungetc function is a function in the C language standard library, used to push a character back into the input stream.

Function parameters:

c: The character to be pushed back.

stream: The file pointer to be pushed back.

Function return value:

Success: Returns the character c that was successfully pushed back.

Failure: returns EOF (-1).

Ungetc function principle

 Figure 1-1 Principle of ungetc function

Compared with other single character processing functions, the ungetc function is a little more difficult to understand. There is a lot of information on the Internet discussing the ungetc function, and sometimes it can really get confusing.

In fact, if we read the glibc source code carefully, we can find that the ungetc function only moves the _IO_read_ptr pointer back by one byte, and then fills the character that needs to be pushed back to the byte, so that the byte can be read again next time.

The main function of ungetc function is a preview function.


Things to note when using the ungetc function

  • The ungetc function can only push back one character, even if the character c passed in is a multibyte character.
  • The ungetc function can only push characters back into the read buffer and cannot be used to change the file pointer position.

1.1.5 Comprehensive example code for single-character file reading

int single_char_read_test() {
    int c = 0;
#if 1
    FILE *fp = fopen(TEST_FILE, "r+");
    if (!fp) {
        perror("fopen error");
        return -1;
    }
#else
    FILE *fp = stdin;
#endif
    c = fgetc(fp);
    putchar(c);
    c = getc(fp);
    putchar(c);
    c = getchar();
    putchar(c);

    ungetc('+', fp);
    c = fgetc(fp);
    putchar(c);

    if (fp != stdin) {
        fclose(fp);
    }
    return 0;
}

1.2 Single character writing file

1.2.1 fputc function

#include <stdio.h>

int fputc(int c, FILE *stream);

Function introduction: The fputc function is a function in C language used to write a character to a specified file.

Function parameters:

c: Indicates the character to be written, passed as an integer.

stream: Represents the file pointer to be written.

Function return value:

Success: Returns the character written successfully.

Failure: returns EOF (-1).

1.2.2 putc function

#include <stdio.h>

int putc(int c, FILE *stream);

Function introduction: The putc function is a function in C language used to write a character to a specified file.

Function parameters:

c: Indicates the character to be written, passed as an integer.

stream: Represents the file pointer to be written.

Function return value:

Success: Returns the character written successfully.

Failure: returns EOF (-1).

1.2.3 putchar function

#include <stdio.h>

int putchar(int c);

Function introduction: The putchar function is a function in the C language standard library, which is used to output a character to the standard output stream (stdout).

Function parameters:

c: Indicates the character to be written, passed as an integer.

Function return value:

Success: Returns the character written successfully.

Failure: returns EOF (-1).

1.2.4 Comprehensive sample code for single-character file writing

int single_char_write_test() {
#if 0
    FILE *fp = fopen(TEST_FILE, "r+");
    if (!fp) {
        perror("fopen error");
        return -1;
    }
#else
    FILE *fp = stdout;
#endif
    fputc('a', fp);
    putc('b', fp);
    putchar('c');

    if (fp != stdout) {
        fclose(fp);
    }
    return 0;
}

2. Multi-character file reading and writing

2.1 Multi-character reading file

2.1.1 fgets function

#include <stdio.h>

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

Function introduction: The fgets function is a function in C language used to read a line of data from a specified file.

Function parameters:

s: Represents a character array used to store the read string data.

size: Indicates the maximum number of characters to be read.

stream: Represents the file pointer to be read.

Function return value:

Success: Returns a pointer to s.

Failure: If the read fails or the end of the file has been reached, NULL is returned.

Precautions:

  • The fgets function will limit the number of characters read according to the specified size, and will stop reading when it encounters a newline character ('\n') or end-of-file character (EOF).
  • fgets will replace the last character read with the terminator ('\0'). Especially when the size is limited, it will usually be one character less than the number of characters read (size) because the last character is replaced. into the terminator ('\0').

2.1.2 gets function

#include <stdio.h>

char *gets(char *s);

Function introduction: The gets function is a function used to read a line of string from the standard input (stdin). The gets function will read characters from the standard input until it encounters a newline character ('\n'), and will read The retrieved characters are stored in the character array pointed to by str. It automatically adds the string terminator ('\0').

Since the gets function cannot check the length of the input characters, it can easily lead to buffer overflow. This makes the gets function very unsafe and vulnerable to buffer overflow attacks, which may cause the program to crash or be maliciously exploited.

Function parameters:

s: Represents a character array used to store the read string data.

Function return value:

Success: Returns a pointer to s.

Failure: If the read fails or the end of the file has been reached, NULL is returned.

2.1.3 Comprehensive sample code for reading multi-character files

int multil_char_read_test() {
    char rbuf[BUF_SIZE] = {0};
#if 0
    FILE *fp = fopen(TEST_FILE, "r+");
    if (!fp) {
        perror("fopen error");
        return -1;
    }
#else
    FILE *fp = stdin;
#endif
    memset(rbuf, 0, BUF_SIZE);
    char *p = fgets(rbuf, 10, fp);
    printf("p:%s\n", p);
    printf("rbuf:%s\n", rbuf);

    if (fp != stdin) {
        fclose(fp);
    }
    return 0;
}

2.2 Writing files with multiple characters

2.2.1 fputs function

#include <stdio.h>

int fputs(const char *s, FILE *stream);

Function introduction: The fputs function is a function in C language used to write strings to specified files.

Function parameters:

s: Indicates the string data to be written.

stream: Represents the file pointer to be written.

Function return value:

Success: Returns a non-negative integer.

Failure: returns EOF (-1).

2.2.2 puts function

#include <stdio.h>

int puts(const char *s);

Function introduction: The puts function is a function in C language used to print a string to the standard output (stdout). The puts function will print the string to the standard output and automatically add a newline character ('\n') at the end of the string. .

Function parameters:

s: Indicates the string data to be written.

Function return value:

Success: Returns a non-negative integer.

Failure: returns EOF (-1).

2.2.3 Comprehensive sample code for writing multi-character files

int multil_char_write_test() {
    char wbuf[BUF_SIZE] = {0};
#if 1
    FILE *fp = fopen(TEST_FILE, "r+");
    if (!fp) {
        perror("fopen error");
        return -1;
    }
#else
    FILE *fp = stdout;
#endif

#define TEST1_STRING "helloworld\n"
    memset(wbuf, 0, BUF_SIZE);
    memcpy(wbuf, TEST1_STRING, sizeof(TEST1_STRING));
    printf("wbuf:%s\n", wbuf);
    int ret = fputs(wbuf, fp);
    printf("fputs ret:%d\n", ret);
    if (ret == EOF) {
        perror("fputs error");
        goto out;
    }
    ret = puts(TEST_STRING);
    printf("puts ret:%d\n", ret);
    if (ret == EOF) {
        perror("puts error");
        goto out;
    }

out:
    if (fp != stdout) {
        fclose(fp);
    }
    return 0;
}

3. Binary reading and writing

3.1 Binary file reading

3.1.1 fread function

#include <stdio.h>

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

Function introduction: The fread function is a function in the C language standard library, used to read data from files.

Function parameters:

ptr: Pointer to a memory area used to store read data.

size: The number of bytes per data element.

nmemb: The number of data elements to be read.

stream: Pointer to file object.

Function return value:

Success: The number of data elements actually successfully read, usually equal to the parameter nmemb.

Failure: If an error occurs or the end of file is reached, the return value may be less than the parameter nmemb (usually 0).

3.1.2 fread function sample code

int fread_test() {
    int ret = 0;
    char rbuf[BUF_SIZE] = {0};
    FILE *fp = fopen(TEST_FILE, "r+");
    if (!fp) {
        perror("fopen error");
        return -1;
    }

    memset(rbuf, 0, BUF_SIZE);

    int count = 2;
    while((ret = fread(rbuf, 100, count, fp)) == count) {
        printf("ret:%d\n", ret);
    }
    printf("break ret:%d\n", ret);

    fclose(fp);

    return 0;
}

3.2 Binary writing file

3.2.1 fwrite function

#include <stdio.h>

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

Function introduction: The fwrite function is a function in the C language standard library, used to write data to files.

Function parameters:

ptr: Pointer to the data to be written to the file.

size: The number of bytes per data element.

nmemb: The number of data elements to be written.

stream: Pointer to file object.

Function return value:

Success: The actual number of data elements written successfully, usually equal to the parameter nmemb.

Failure: If an error occurs, the return value may be less than the parameter nmemb (usually 0).

3.2.2 fwrite function sample code

int fwrite_test() {
    char sbuf[BUF_SIZE] = {0};
    for (int i = 0; i < BUF_SIZE; i++) {
        sbuf[i] = 'S';
    }

    FILE *fp = fopen(TEST_FILE, "w+");
    if (!fp) {
        perror("fopen error");
        return -1;
    }
    int count = 5;
    int ret = fwrite(sbuf, BUF_SIZE, count, fp);
    printf("fwrite count:%d, ret:%d\n", count, ret);
    if (ret != count) {
        perror("fread error");
        goto out;
    }

out:
    fclose(fp);

    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_28673511/article/details/131952061