C/C++ development, unavoidable IO input/output (Part 4). Brief introduction to c implementation

Table of contents

一、C-IO

2. File operation IO

3. String stream (memory stream) IO

4. Device abstraction IO


一、C-IO

        The IO input/output of the c language is provided by the standard library <stdio.h>. As the name implies, stdio is the IO module of the standard library (std). The <stdio.h> header file provides general file manipulation support and provides functions capable of narrow character input/output. For wide characters, <wchar.h> is added as an auxiliary, this header file provides functions with wide character input/output capabilities. The I/O flow of c language is represented by FILE object, which can only be accessed and operated through FILE* type pointer. Each stream is associated with an external physical device (file, standard input stream, printer, serial port, etc.).

        Let's take a look at the main functions of stdio:

//定义于头文件 <stdio.h>
FILE      对象类型,足以保有控制 C I/O 流所需的全部信息(typedef) 
fpos_t    非数组完整对象类型,足以唯一指定文件的位置和多字节剖析状态(typedef) 

//预定义标准流
stdin     与标准输入流关联的 FILE* 类型表达式(宏常量) 
stdout    与标准输出流关联的 FILE* 类型表达式(宏常量) 
stderr    与标准错误输出流关联的 FILE* 类型表达式(宏常量) 

//函数,文件访问
fopen      (C11)打开文件(函数) 
fopen_s    (C11)打开文件(函数) 

freopen    (C11)以不同名称打开既存的文件流(函数) 
freopen_s  (C11)以不同名称打开既存的文件流(函数) 

fclose     关闭文件(函数) 
fflush     将输出流与实际文件同步(函数) 
setbuf     为文件流设置缓冲区(函数) 
setvbuf    为文件流设置缓冲区和其大小(函数) 

//直接输入/输出
fread    从文件读取(函数) 
fwrite   写入到文件(函数) 

//无格式输入/输出,窄字符
fgetc    从文件流获取一个字符(函数) 
getc     从文件流获取一个字符(函数) 

fgets    从文件流获取一个字符串(函数) 
fputc    将一个字符写入文件流(函数) 
putc     将一个字符写入文件流(函数) 
fputs    将一个字符串写入文件流(函数) 

getchar  从 stdin 读取一个字符(函数) 
gets     (C11 中移除)从 stdin 读取一个字符串(函数) 
gets_s   (C11)从 stdin 读取一个字符串(函数) 
putchar  将一个字符写入 stdout(函数) 
puts     将一个字符串写入 stdout(函数) 
ungetc   将一个字符送回文件流(函数) 

//有格式输入/输出,窄字符 
scanf        从stdin、文件流或缓冲区读取格式化输入(函数) 
fscanf       ...
sscanf       ... 
scanf_s      (C11)...
fscanf_s     (C11)...
sscanf_s     (C11)...

vscanf       (C99)从 stdin 、文件流或缓冲区读取格式化输入 使用可变参数列表(函数) 
vfscanf      (C99)...
vsscanf      (C99)...
vscanf_s     (C11)...
vfscanf_s    (C11)...
vsscanf_s    (C11)...

printf      打印格式化输出到 stdout 、文件流或缓冲区(函数) 
fprintf     ...
sprintf     ...
snprintf    (C99)...
printf_s    (C11)...
fprintf_s   (C11)...
sprintf_s   (C11)...
snprintf_s  (C11)...

vprintf     打印格式化输出到stdout、文件流或缓冲区 使用可变参数列表(函数) 
vfprintf    ...
vsprintf    ...  
vsnprintf   (C99)...
vprintf_s   (C11)...
vfprintf_s  (C11)...
vsprintf_s  (C11)...
vsnprintf_s (C11)...

//文件位置
ftell       返回当前的文件位置指示值(函数) 
fgetpos     获取文件位置指示器(函数) 
fseek       将文件位置指示符移动到文件中的指定位置(函数) 
fsetpos     将文件位置指示器移动到文件中的指定位置(函数) 
rewind      将文件位置指示器移动到文件首(函数) 

//错误处理
clearerr   清除错误(函数)
feof       检查文件结尾(函数) 
ferror     检查文件错误(函数) 
perror     显示对应当前错误的字符串到 stderr(函数) 

//文件操作
remove     删除文件(函数) 
rename     重命名文件(函数) 
tmpfile    返回指向临时文件的指针(函数)
tmpfile_s  (C11) ...
tmpnam     返回唯一的文件名(函数) 
tmpnam_s   (C11) ...
 
//宏常量
EOF            int 类型的负值整数常量表达式(宏常量) 
FOPEN_MAX      能同时打开的文件数(宏常量) 
FILENAME_MAX   保有最长受支持文件名所需的 char 数组大小(宏常量)
BUFSIZ         setbuf() 所用的缓冲区大小(宏常量) 
_IOFBF         指示全缓冲 I/O 的 setvbuf() 参数(宏常量)
_IOLBF         指示行缓冲 I/O 的 setvbuf() 参数(宏常量)
_IONBF         指示无缓冲 I/O 的 setvbuf() 参数(宏常量)

SEEK_SET       指示从文件首开始寻位的 fseek() 参数(宏常量) 
SEEK_CUR       指示从文件当前位置开始寻位的 fseek() 参数(宏常量)
SEEK_END       指示从文件尾开始寻位的 fseek() 参数(宏常量) 

TMP_MAX        tmpnam 所能生成的最大独有文件数(宏常量) 
TMP_MAX_S      (C11)tmpnam_s 所能生成的最大独有文件数(宏常量) 
L_tmpnam       保有 tmpnam 结果所需的 char 数组大小(宏常量) 
L_tmpnam_s     (C11)保有 tmpnam_s 结果所需的 char 数组大小(宏常量) 

2. File operation IO

        In general, file operations have the following steps:

  1. Define the file pointer and open the file;
  2. Read and write operations through file pointers;
  3. Close the file.

        The following is a simple example to demonstrate how to implement file input and output operations:

//main.c,gcc main.c -o test.exe -std=c11
#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp;
    char ch, filename[10];
    printf("请输入文件名:");
    scanf("%s", filename);
    fp = fopen(filename, "w"); // 以写入方式打开文件,如果文件不存在则新建文件
    if (fp == NULL)
    {
        printf("无法打开文件\n");
        exit(0);
    }
    printf("请输入内容:\n");
    while ((ch = getchar()) != EOF) // 从键盘读取字符,直到EOF结束
    {
        fputc(ch, fp); // 将字符写入到文件中
    }
    fclose(fp); // 关闭文件
    printf("写入成功\n");

    fp = fopen(filename, "r"); // 以读取方式打开文件
    if (fp == NULL)
    {
        printf("无法打开文件\n");
        exit(0);
    }
    printf("读取内容:\n");
    while ((ch = fgetc(fp)) != EOF) // 从文件中读取字符,直到EOF结束
    {
        putchar(ch); // 将字符输出到屏幕
    }
    fclose(fp); // 关闭文件
    return 0;
}

        The code prompts the user for a filename, then opens the file for writing, and writes the user's keyboard input into the file. Next, open the same file for reading, and read and output the contents of the file to the screen. You can check whether the input and output of the file is successful by running the program.

3. String stream (memory stream) IO

        There is no built-in string stream function in C language, but it can be simulated manually by the following methods:

        1. Create a buffer as the output source of the string stream

char buffer[1024]; // 创建一个大小为1024的缓冲区

        2. Use sprintf to format the data to be output into the buffer

int x = 10;
float y = 3.14;
char str[] = "hello";
sprintf(buffer, "x=%d, y=%.2f, str=%s", x, y, str);

        3. Read the string stream data from the buffer

char result[1024];
strcpy(result, buffer);

        The above is a basic way of manually simulating string streams. If you need more advanced features similar to string streams in C++, such as overloaded operators, custom input/output operators, etc., you can use C++ to write.

4. Device abstraction IO

        The device abstract IO of C language is mainly the interaction with the command window, which is mainly realized through the predefined standard stream.

stdin     与标准输入流关联的 FILE* 类型表达式
stdout    与标准输出流关联的 FILE* 类型表达式
stderr    与标准错误输出流关联的 FILE* 类型表达式  
 

        The predefined standard stream is essentially a FILE* pointer operation. You can use the functions provided by the stdio.h header file in the standard library to perform screen input/output operations. Commonly used functions include printf and scanf.

        The printf function can output formatted text for outputting content to the screen:

//main.c,gcc main.c -o test.exe -std=c11
#include <stdio.h>

int main(void) {
    printf("Hello, world!\n");
    return 0;
}

        And fprintf can specify the output of FILE* types such as global stdout and stderr

//main.c,gcc main.c -o test.exe -std=c11
#include <stdio.h>

int main(void) {
    fprintf(stdout,"Hello, world!\n");
    return 0;
}

        The scanf function can read data input from the screen and store the data into variables:

//main.c,gcc main.c -o test.exe -std=c11
#include <stdio.h>

int main(void) {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("You entered: %d\n", num);
    return 0;
}

        Of course, similarly, fscanf can specify input from FILE* types such as global stdin

//main.c,gcc main.c -o test.exe -std=c11
#include <stdio.h>

int main(void) {
    int num;
    printf("Enter a number: ");
    fscanf(stdin,"%d", &num);
    printf("You entered: %d\n", num);
    return 0;
}

        In addition to the above two functions, C language also provides many other screen input/output functions, such as puts function, gets function, fgets function, puts function, etc., which can be selected and used according to specific needs.

        The functions applicable to screen input and output are more applicable to file operations. Comparing screen input and output is essentially a FILE* type operation.

Guess you like

Origin blog.csdn.net/py8105/article/details/129909470