Chapter 13 file input and output

First, the document outlines

1.1 File concept

File is usually on a disk or solid-state drive for a named storage area. C the documents as a series of successive bytes, each byte can be read individually. C provides two file modes: text mode and binary mode.

1.2 text mode and binary mode

1.2.1 text and binary content

The contents of all files are in binary form (0 or 1) storage. However, if the file was originally binary-coded character (for example, ASCLL or Unicode) representing text, the file is a text file that contains the text content; if the file in binary represents the machine language code or numerical data or pictures or music coding, the file is a binary file that contains the binary content.

1.2.2 text mode and binary mode

In order to standardize processing, C language provides two text files access to files Drang: binary and text mode. In binary mode, the program can access each byte of the file; in text mode, the actual content of the program content and document seen not the same.

Program to read and write files in text mode, the end of the line or the end of file in the local environment represented by the map to the C mode. For example, program C reads the file in text mode old Maciontosh in the \ r mapped to a file \ n; when data is written in text mode, the \ n converted to \ r.

When the program to read and write files in binary mode, the program will not see the files in the \ r and \ n, the mapping does not occur.

Although C provides binary and text mode, but the implementation of these two modes may be identical, for example, UNIX and Linux does the exact same method of the two modes.

1.3 I / O level

In addition to selecting the file mode, you can also choose two levels of I / O: the underlying I / O standard and advanced I / O. The underlying I / O operating system provides the basic I / O services; Advanced standard I / O using the standard package and the stdio.h header file defines the C library.

Second, the standard I / O

2.1 standard document

C program will default to open three files: standard input, standard output and standard error output.

By default, the input device is a common standard input system, usually the keyboard; standard output device is generally normal output system, usually a display screen.

Example:

/*本例实在 linux 环境中运行的,open 为系统调用,头文件是 open 函数所需要的文件。*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(void)
{
        int fd;

        //获得文件描述符
        fd = open("./array1.c", O_RDONLY);
        printf("fd is: %d\n", fd);

        return 0;
}
/*运行结果
fd is: 3
*/

Analysis of Results: fd = 3, have been described in 0,1,2 file is opened, that is, the above-described standard input, standard output and standard error.

2.2 exit () function

exit () function to close all open files and the program ends, passing its parameters to some of the operating system, for use by other programs, like in UNIX parent will tell how it's not. 0 transfer procedure normally ended, the abnormally ended program passes non-zero value, corresponding to different values ​​for different reasons exit.

ANSI C provides the use of the same in return the initial main () call with the call exit () effect.

Difference:

Ⅰ. If the main () procedure in a recursive, Exit () will directly terminate the program, but will return a return recursion.

Ⅱ. In other functions, exit () may terminate the entire program.

2.3 standard I / O functions

2.3.1 fopen()

After the success of the program to open the file, fopen () returns the file pointer. Type FILE file pointer is a pointer to a pointer.

2.3.2 getc() 和 putc()

getc () and putc () and getchar () and putchar () function is similar, except that, getc () and putc () you can specify a file, getchar () and putchar () files can only be stdin and stdout .

Example:

#include <stdio.h>

int main(void)
{
        FILE *rfp;      //读文件的指针
        FILE *wfp;      //写文件的指针
        char ch;

        rfp = fopen("./read", "r");
        wfp = fopen("./write","w");

        while((ch = getc(rfp)) != EOF)
        {
                putc(ch, wfp);  //向 write.c 中写入
                putc(ch, stdout);       //向屏幕输出
        }
    
    	//保存文件
        if(fclose(wfp) != 0)
                printf("Error in closing file write\n");

        return 0;
}

2.3.3 fclose()

flcose () function closes the file specified by fp, flush buffers if necessary. If successfully closed, fclose () returns 0, otherwise it returns EOF.

2.3.5 fscanf () and fprintf () (Note: This is not a standard I / O, file I / O)

These two functions are similar to scanf () and printf ().

Example:

/*fprintf() demo*/
#include <stdio.h>

int main(void)
{
        FILE *file;
        double d = 0.3333;
        char *a = "aldskjf";

        file = fopen("fprintf", "w");   //打开文件
        fprintf(file, "%.2f\n%s\n", d, a);      //写入 file 文件中
        fprintf(stdout, "%.2f\n%s\n", d, a);    //写入标准输出中

        return 0;
}
/*fscanf() demo*/
#include <stdio.h>

int main(void)
{
        FILE *file;
        char words[50];

        file = fopen("fprintf", "r");
        while(fscanf(file, "%s", words) == 1)   //从 file 文件中读取内容输出到屏幕
                puts(words);

        return 0;
}

2.3.6 fread() 和 fwrite()

Two I / O functions previously mentioned are text-oriented, and for processing character string. When used for transformation% to save the value, but the value is converted into character data value may change, the change is irreversible. To ensure consistency in the values ​​before and after the storage, the most accurate approach is to use a computer to store the same bit. This conversion process from digital form to the string does not exist. This kind of notation used in the program is stored in the data processing method is referred to as file data in binary form.

Example:

/*fwrite() demo*/
#include <stdio.h>
#define SIZE 7

int main(void)
{
        FILE *arrayfile;
        //定义一个 double 数组
        double array[SIZE] = {4, 5, 1, 1, 4, 6, 7};

        arrayfile = fopen("array", "wb");	//以二进制的形式打开文件
        fwrite(array, sizeof(double), 7, arrayfile);    //把数组中内容写到 books 文件中
		
        fclose(arrayfile);

        return 0;
}
/*结果:
存在文件中的数据(二进制编码):
^@^@^@^@^@^@^P@^@^@^@^@^@^@^T@^@^@^@^@^@^@ð?^@^@^@^@^@^@ð?^@^@^@^@^@^@^P@^@^@^@^@^@^@^X@^@^@^@^@^@^@^\@
*/
/*fread() demo*/
#include <stdio.h>
#define SIZE 7

int main(void)
{
        int i;
        FILE *arrayfile;                //文件指针
        double array[SIZE];

        arrayfile = fopen("array", "rb");       //以二进制的形式打开 array
        fread(array, sizeof(double), SIZE, arrayfile);  //把文件中的内容读到结构数组中 

        //输出
        printf("array: \n");
        for(i = 0; i < SIZE; i++)
                printf("%.2f ", array[i]);
        printf("\n");

        return 0;
}
/*运行结果
array: 
4.00 5.00 1.00 1.00 4.00 6.00 7.00 
*/

2.3.7 Buffer

Standard I / O of the first step is to call the fopen () function. fopen () not to open a file, a buffer is also created (create two buffers in read-write mode), and to give structure comprising buffered data and files.

File input. Using standard I / O calls Step 2 is a defined in stdio.h input function, such as fscanf (), getc (). A call these functions, the buffer size of data blocks of the file is copied to the buffer.

File output. Similar to the way data is written to the file input buffer. When the buffer is full, data will be copied to the file.

Standard I / O read and write files to greatly simplify, do not reflect the buffers in the program, only need to write directly on it.

Example:

/*Linux 的底层级别读写文件 */
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char * argv[])
{
        int rfd;        //读文件的 fd
        int wfd;        //写文件的 fd
        char buf[512];
        ssize_t n;
    
        printf("%s\n%s\n", argv[1], argv[2]);
        //打卡文件
        rfd = open(argv[1], O_RDONLY);	//读模式
        wfd = open(argv[2], O_WRONLY|O_CREAT);		//写模式,没有就创建一个

        while((n = read(rfd, buf, sizeof(buf))) >  0)	//读文件,linux 如果没有读到末尾,n>0
        {
                printf("%zd\n", n);		//输出读了多少内容
                write(wfd, buf, n);		//写文件
        }

        close(rfd);
        if(close(wfd) == 0)	//保存文件,linux 中如果成功保存 close 返回 0
                printf("write successfully\n");

        return 0;
}

As can be seen, the use of the underlying level I / O read and write files more step, comparison, much simpler procedure 2.3.2.

Reference books

C Primer Plus (sixth edition) Chinese version

Published 42 original articles · won praise 3 · Views 2084

Guess you like

Origin blog.csdn.net/stable_zl/article/details/104147975
Recommended