C standard library - Detailed explanation of <stddef.h> and <stdio.h>

Table of contents

C standard library - 

Introduction

library variables

Kuhong

Example

C standard library - 

Introduction

library variables

Kuhong

Library Functions

Example


C Standard Library - <stddef.h>

Introduction

<stdio.h> is a standard library in the C language that provides some commonly used functions and type definitions for handling size-related operations.

library variables

The types defined in <stddef.h> are:

  1. size_t: unsigned integer type used to represent the size of the object.
  2. ptrdiff_t: Signed integer type used to represent the difference between two pointers.
  3. wchar_t: wide character type, used when processing wide characters.

These types are frequently used in standard library functions in C to provide support for sizes, pointer operations, and wide characters.

Kuhong

<stddef.h> Some commonly used macros are defined in the header file.

  1. NULL: The value of a null pointer constant.
  2. offsetof(type, member-designator): Generates an integer constant of type size_t, which represents the byte offset of the structure member relative to the starting position of the structure. Among them, type represents the structure type, and member-designator represents the identifier of the structure member.

It is worth noting that the offsetof macro can only be used for structures and unions in standard data types, and cannot be used for bit fields. When using it, you should follow the specifications of the C language. At the same time, you need to note that different compilers may have differences in their implementation methods.

Example

#include <stdio.h>
#include <stddef.h>

int main() {
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    size_t size = sizeof(arr); // 计算数组 arr 的大小
    ptrdiff_t diff = &arr[5] - &arr[0]; // 计算指针差值
    printf("数组 arr 的大小为 %zu\n", size); // 使用 %zu 输出 size_t 类型
    printf("&arr[5] - &arr[0] 的差值为 %td\n", diff); // 使用 %td 输出 ptrdiff_t 类型
    struct Person {
        char name[20];
        int age;
        double height;
    };
    size_t offset = offsetof(struct Person, age); // 计算结构体成员偏移量
    printf("结构体成员 age 在结构体中的偏移量为 %zu\n", offset); // 使用 %zu 输出 size_t 类型
    return 0;
}

In this example, we first define an integer array arr, then use sizeof to calculate the size of the array, and use the & operator to obtain the addresses of two elements in the array for calculating the pointer difference. Then we defined a structure named Person, used the offsetof macro to calculate the offset of the structure member age relative to the starting position of the structure, and output the result to the screen. Finally, 0 is returned to indicate that the program ends normally.

It is worth noting that when using the size_t and ptrdiff_t types, we use %zu and %td respectively as placeholders for formatted output. This is because size_t is an unsigned integer type, and ptrdiff_t is a signed integer type, and their output format is different from ordinary integer types.

Let's compile and run the above program, which will produce the following results:

数组 arr 的大小为 40
&arr[5] - &arr[0] 的差值为 5
结构体成员 age 在结构体中的偏移量为 20

C Standard Library - <stdio.h>

Introduction

<stdio.h> is a header file in the C standard library that defines variable types, macros, and functions related to input and output. This header file provides support for standard input, standard output, and file operations.

library variables

  1. size_t: This is an unsigned integer type used to represent the size of an object. Typically used as the result of the sizeof operator. For example, you can use size_t to represent the size of an array or the length of a buffer.

  2. FILE: This is a structure type used to represent file stream information. It contains all the information required to operate the file, such as file pointers, file status flags, read and write locations, etc. By using pointers of type FILE, we can open, close, read and write files.

  3. fpos_t: This is a type used to store information anywhere in a file. It can represent any offset in the file. Variables of type fpos_t are often used with functions such as fseek and fgetpos to locate and operate on files.

Kuhong

The following are macros defined in the header file stdio.h:

  1. NULL: This is the value of a null pointer constant. Typically used to initialize pointer variables to indicate that they do not point to any valid memory address.

  2. _IOFBF, _IOLBF, and _IONBF: These macros are used in the third parameter of the setvbuf function to set the file's buffering type. _IOFBF means full buffering, _IOLBF means line buffering, and _IONBF means no buffering.

  3. BUFSIZ: This is an integer value representing the buffer size used by the setbuf function. For the standard I/O library, this is usually a larger number (such as 512 or 1024) to allow for more efficient reads and writes.

  4. EOF: This is a negative integer value used to indicate that the end of file has been reached or that a read or write operation has failed. In the standard input and output functions, they return EOF when an end-of-file or error is encountered.

  5. FOPEN_MAX: This is an integer value that represents the number of files that the system can open simultaneously. Typically, its value is a large number (such as 256 or more).

  6. FILENAME_MAX: This is an integer value that represents the maximum length of a file name that can be stored in a character array. If the implementation does not have any restrictions, this value should be the recommended maximum.

  7. L_tmpnam: This is an integer value that represents the maximum length of a character array that can store the name of a temporary file created by the tmpnam function.

  8. SEEK_CUR, SEEK_END, and SEEK_SET: These macros are used for file positioning in the fseek function. They represent the current position, the end of the file and the beginning of the file respectively.

  9. TMP_MAX: This is an integer value that represents the maximum number of unique filenames that can be generated by the tmpnam function.

  10. stderr, stdin, and stdout: These macros are pointers to FILE types, corresponding to the standard error, standard input, and standard output streams respectively. They are often used as default file pointers to facilitate input and output operations.

Library Functions

The following are the functions defined in the header file stdio.h:

To better understand the functions, follow the sequence below to learn the functions, as the files created in the first function will be used in subsequent functions.
serial number Function & Description
1 int fclose(FILE *stream)
Close the stream stream. Flush all buffers.
2 void clearerr(FILE *stream)
Clears the end-of-file and error identifiers of the given stream stream.
3 int feof(FILE *stream)
Tests the end-of-file identifier of the given stream stream.
4 int ferror(FILE *stream)
Tests the error identifier of the given stream stream.
5 int fflush(FILE *stream)
Flushes the output buffer of stream stream.
6 int fgetpos(FILE *stream, fpos_t *pos)
Get the current file position of stream stream and write it to pos.
7 FILE *fopen(const char *filename, const char *mode)
Open the file pointed to by filename using the given mode mode.
8 size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
Read data from the given stream stream into the array pointed to by ptr.
9 FILE *freopen(const char *filename, const char *mode, FILE *stream)
Associates a new file name filename with the given open stream stream, and at the same time Close old files in the stream.
10 int fseek(FILE *stream, long int offset, int whence)
Set the file position of the stream to the given offset offset, parameter offset means the number of bytes to search from the given whence position.
11 int fsetpos(FILE *stream, const fpos_t *pos)
Sets the file position of the given stream stream to the given position. The parameter pos is the position given by the function fgetpos.
12 long int ftell(FILE *stream)
Returns the current file position of the given stream stream.
13 size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
Write the data in the array pointed to by ptr to the given stream stream.
14 removeint remove(const char *filename)
Removes the given filename filename so that it is no longer accessed.
15 int rename(const char *old_filename, const char *new_filename)
Change the file name pointed by old_filename to new_filename.
16 void rewind(FILE *stream)
Sets the file position to the beginning of the file for the given stream stream.
17 void setbuf(FILE *stream, char *buffer)
Defines how the stream stream should be buffered.
18 int setvbuf(FILE *stream, char *buffer, int mode, size_t size)
Another function that defines how the stream should be buffered.
19 FILE *tmpfile(void)
Create a temporary file in binary update mode (wb+).
20 char *tmpnam(char *str)
Generates and returns a valid temporary file name that did not previously exist.
21 int fprintf(FILE *stream, const char *format, ...)
Send formatted output to the stream stream.
22 int printf(const char *format, ...)
Send formatted output to stdout.
23 int sprintf(char *str, const char *format, ...)
Send formatted output to a string.
24 int vfprintf(FILE *stream, const char *format, va_list arg)
Send formatted output to the stream stream using an argument list.
25 int vprintf(const char *format, va_list arg)
Send formatted output to stdout using an argument list.
26 int vsprintf(char *str, const char *format, va_list arg)
Send formatted output to a string using an argument list.
27 int fscanf(FILE *stream, const char *format, ...)
Read formatted input from stream stream.
28 int scanf(const char *format, ...)
Read formatted input from standard input stdin.
29 int sscanf(const char *str, const char *format, ...)
Read formatted input from a string.
30 int fgetc(FILE *stream)
Gets the next character (an unsigned character) from the specified stream stream and moves the position identifier forward.
31 char *fgets(char *str, int n, FILE *stream)
Read a line from the specified stream stream and store it in the string pointed to by str . It stops when (n-1) characters are read, or when a newline character is read, or when the end of the file is reached, depending on the It depends.
32 int fputc(int char, FILE *stream)
Writes the character specified by parameter char (an unsigned character) into the specified stream, and sets the position identifier Move forward.
33 int fputs(const char *str, FILE *stream)
Writes the string to the specified stream stream, but does not include the null character.
34 int getc(FILE *stream)
Gets the next character (an unsigned character) from the specified stream stream and moves the position identifier forward.
35 int getchar(void)
Gets a character (an unsigned character) from standard input stdin.
36 char *gets(char *str)
Reads a line from standard input stdin and stores it in the string pointed to by str. It stops when a newline character is read, or when the end of the file is reached, as the case may be.
37 int putc(int char, FILE *stream)
Writes the character specified by parameter char (an unsigned character) into the specified stream, and sets the position identifier Move forward.
38 int putchar(int char)
Writes the character specified by parameter char (an unsigned character) to the standard output stdout.
39 int puts(const char *str)
Writes a string to standard output stdout up to, but not including, the null character. Newlines are appended to the output.
40 int ungetc(int char, FILE *stream)
Push the character char (an unsigned character) into the specified stream so that it is read next to the characters.
41 void perror(const char *str)
Output a descriptive error message to stderr. The string str is output first, followed by a colon and then a space.
42 int snprintf(char *str, size_t size, const char *format, ...)
format string into str.

Example

#include <stdio.h>

int main() {
    FILE *file;
    char buffer[100];

    // 打开文件以供读取
    file = fopen("D://example.txt", "r");
    if (file == NULL) {
        printf("无法打开文件\n");
        return 1;
    }

    // 从文件读取数据并输出到控制台
    while (fgets(buffer, sizeof(buffer), file)) {
        printf("%s", buffer);
    }

    // 关闭文件
    fclose(file);

    return 0;
}

This example demonstrates how to use the fopen function to open a file, use the fgets function to read data line by line from the file and store it in a buffer, and then use the printf function to output the data to the console. Finally, the file is closed using the fclose function.

Please note that the example assumes that a text file named "example.txt" exists in the current directory and is readable. If the file does not exist or cannot be read, the program will print an error message.

Guess you like

Origin blog.csdn.net/m0_74293254/article/details/134588404