C language | file operation (1)

1. Document overview

1. Disk file

Refers to an ordered collection of a group of related data, usually stored on an external medium (such as a disk), and transferred to the memory when it is used. From the perspective of the user or operating system (logically), the files are divided into text files and binary files.

a. Text file

1. Files based on character encoding, common encodings are ASCII, UNICODE, etc.;

2. Generally, you can use a text editor to open directly;

3. The number 5678 is stored in ASCII format: 00110101 00110110 00110111 00111000.

b. Binary files

1 Based on value-encoded files, you can specify what a certain value means according to your specific application;

2. Output the data in the memory to the disk as it is stored in the memory;

3. The number 5678, in the form of binary storage: 00010110 00101110.

2. Equipment files

In the operating system, each input and output device connected to the host is regarded as a file, and their input and output are equivalent to reading and writing to disk files.

2. Operations on text files

1. Open the file

(1) Function

#include<stdio.h>

FILE* fopen(const char* filename,const char* mode);

Parameters: filename: the name of the file to be opened (including path)

           mode: The mode setting for opening the file  

Return value: success: file pointer; failure: NULL

(2) The mode of opening the file

Open mode meaning Remarks
r or rb Open a text file in read-only mode (an error will be reported if the file does not exist)

1.b means binary, only valid in windows, the result of using r and rb in Linux is the same.

2. All text file lines under Unix and Linux end with \n, while all text file lines under Windows end with \r\n.

3. Under Unix and Linux, there is no difference between "text" and "binary" mode, "\r\n" is input and output as two characters as it is

4. Under Windows, open the file in "text" mode, that is, when b is not added:

  a. When reading the file, the system will convert all \r\n to \n

  b. When writing a file, the system will convert \n to \r\n

5. Under Windows, when opening a file in "binary" mode, the conversion between \r\n and \n will not be performed

 

 

 

w or wb Open the file for writing (empty if the file exists, create if the file does not exist)
a or ab Open the file by appending and add content at the end (create if the file does not exist)
r+ or rb+ Open the file in a readable and writable way (if the file does not exist, an error will be reported)
w+ or wb+ Open the file in a readable and writable way (empty if the file exists, or create if the file does not exist)
a + or ab + Open the file by appending and add content at the end (create if the file does not exist)

2. Close the file

(1) The significance of closing the file

1. Open files will take up memory resources, if they are always opened but not closed, a lot of memory will be consumed.

2. The number of files opened simultaneously by a process is limited. If the maximum number of files opened simultaneously is exceeded, calling fopen again to open the file will fail.

3. If you do not explicitly call fclose to close the open file, the operating system will close the program when the program exits.

(2) Function

#include<stdio.h>

int fclose(FILE* stream);

Parameters: stream: file pointer

Return value: Success: 0; Failure: -1

3. Read and write files according to characters

(1) Write file

#include<stdio.h>

int fputc(int ch,FILE* stream);

Parameters: ch: the characters that need to be written to the file

           stream: file pointer

Return value: Success: characters written to the file successfully; failure: -1

(2) Read files

#include<stdio.h>

int fgetc(FILE* stream);

Parameters: stream: file pointer

Return value: Success: the characters read successfully; failure: -1

(3) Detect the end of the file

1.EOF:#define EOF (-1)

In C language, EOF stands for end of file (end of file). In the while loop, EOF is used as the end-of-file mark. The file with EOF as the end-of-file mark must be a text file. In text files, data is stored in the form of character ASCII code values. The range of ASCII code values ​​is 0 ~ 127, and -1 is impossible, so EOF can be used as the end of file mark.

2.feof(): It is the last "read operation content" that is judged, not the current position content (previous content)

When the data is stored in the file in binary form, there will be a value of -1, so EOF cannot be used as the end of the binary file. To solve this problem, ANSI C provides a feof function to determine whether the file is End. The feof function can be used to judge both binary files and text files.

#include<stdio.h>

int feof(FILE* stream);

Parameters: stream: file pointer

Return value: non-zero: the end of the file has been reached; 0: the end of the file has not been reached

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void main()
{
    //以写的模式打开文件
    FILE* fp1 = fopen("D:/c.txt", "w");
    int ch = 'h';
    //以字符的形式写入文件
    fputc(ch, fp1);
    //关闭文件
    fclose(fp1);
    

    //以读的模式打开文件
    FILE* fp2 = fopen("D:/c.txt", "r");
    if (!fp2)
    {
        return;
    }
    //feof:判断是否到了文件结尾
    while (!feof(fp2))
    {
        //以字符的形式读文件,文件在读取时光标流会自动向下移动
        char c = fgetc(fp2);
        printf("%c", c);//h
    }
    //关闭文件
    fclose(fp2);
}

4. Read and write files by line

(1) Write file

#include<stdio.h>

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

Parameters: str: string

           stream: file pointer

Return value: Success: 0; Failure: -1

(2) Read files

#include<stdio.h>

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

Parameters: str: string

          size: Specify the length of the maximum read string

           stream: file pointer

Return value: Success: the string read successfully; read to the end of the file or error: NULL

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string>
void main()
{
    FILE* fp1 = fopen("D:/c.txt", "w");
    //const char* ch = "hello world\n !";
    char ch[] = "hello world\n !";
    fputs(ch, fp1);//一共两行,即fputs不会自动在结尾加一个\n,字符串结束符\0不会写入文件
    fclose(fp1);

    FILE* fp2 = fopen("D:/c.txt", "r");
    if (!fp2)
    {
        return;
    }
    char* data=(char*)malloc(sizeof(char)*20);
    while (!feof(fp2))
    {
        fgets(data, 20, fp2);//会自动加上\0作为字符串结束
        printf("%s", data);
    }
    fclose(fp2);
    free(data);
}
//输出结果:
//hello world 
// !
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string>
#include <time.h>

void main()
{
    srand((size_t)time(NULL));
    int a, b, c;
    char* p = (char*)malloc(sizeof(char) * 20);
    FILE* fp = fopen("D:/加减乘除.txt", "w");
    for (size_t i = 0; i < 10; i++)
    {
        a = rand() % 10 + 1;//1~10的数
        b = rand() % 10 + 1;
        c = rand() % 4;//0~3的数
        memset(p, 0, 20);
        switch (c)
        {
        case 0:
            sprintf(p, "%d+%d=\n", a, b);//按格式化将数据写入字符串
            break;
        case 1:
            sprintf(p, "%d-%d=\n", a, b);
            break;
        case 2:
            sprintf(p, "%d*%d=\n", a, b);
            break;
        case 3:
            sprintf(p, "%d/%d=\n", a, b);
            break;
        default:
            break;
        }
        fputs(p, fp);
    }
    fclose(fp);
    free(p);
}

//加减乘除.txt文件内容:(11行)
8*10=
9*6=
2+7=
7+10=
10/2=
9/5=
7/6=
10*6=
6*8=
9/6=
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string>
#include <time.h>

void main()
{
    FILE* fp1 = fopen("D:/加减乘除.txt", "r");
    if (!fp1)
    {
        return;
    }
    FILE* fp2 = fopen("D:/加减乘除结果.txt", "w");
    char* p = (char*)malloc(sizeof(char) * 20);
    int a, b, value;
    char c;
    while (!feof(fp1))
    {
        memset(p, 0, 20);
        a = 0; b = 0; c = ' ';
        fgets(p, 20, fp1);
        
        sscanf(p, "%d%c%d=", &a, &c, &b);//按格式化读字符串中的数据 
        if (a == 0)//除掉最后一行 
        {
            break;
        }
        switch (c)
        {
        case '+':value = a + b;
            break;
        case '-':value = a - b;
            break;
        case '*':value = a * b;
            break;
        case '/':value = a / b;
            break;
        default:
            break;
        }
        sprintf(p, "%d%c%d=%d\n", a, c, b, value);
        fputs(p, fp2);
    }
    free(p);
    fclose(fp1);
    fclose(fp2);
}

//加减乘除结果.txt文本内容:(11行)
8*10=80
9*6=54
2+7=9
7+10=17
10/2=5
9/5=1
7/6=1
10*6=60
6*8=48
9/6=1

5. Read and write files in accordance with the format

Similar to sscanf and sprintf in the above example.

(1) Write file

#include<stdio.h>

int fprintf(FILE* stream,const char* format,...);

Convert and format data according to the parameter format string, and then output the result to the file specified by stream

Parameters: stream: file pointer

           format: string format, the format is the same as printf()

Return value: Success: the number of characters actually written to the file; failure: -1

(2) Read files

#include<stdio.h>

int fscanf(FILE* stream,const char* format,...);

Read the string from the file specified by stream, and convert and format the data according to the parameter format string. When a space is encountered, the newline ends

Parameters: stream: file pointer

           format: string format, the format is the same as scanf()

Return value: Success: the number of successfully converted values; failure: -1

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

void main()
{
    FILE* fp1 = fopen("D:/info.txt", "w");
    char name[] = "Lisa";
    int age = 25;
    fprintf(fp1, "%s's age is %d,\0 she is a girl", name, age);
    fclose(fp1);
}

//info.txt文本内容:
Lisa's age is 25,
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

void main()
{
    FILE* fp1 = fopen("D:/info.txt", "w");
    char name[] = "Lisa";
    int age = 25;
    fprintf(fp1, "%s's age is %d, she is a\ngirl", name, age);
    fclose(fp1);
}

//info.txt文本内容:
Lisa's age is 25, she is a
girl
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

void main()
{
    //info.txt文本内容:2020 hello world
    FILE* fp = fopen("D:/info.txt", "r");
    if (!fp)
    {
        return;
    }
    
    int a = 0;
    char* info = (char*)malloc(sizeof(char) * 50);
    memset(info, 0, 50);

    fscanf(fp, "%d%s", &a, info); 
    printf("%d,%s",a, info);//2020,hello

    fscanf(fp, "%s", info);
    printf("%s", info);//world
    fclose(fp);
    free(info);
}

6. Read and write binary files in blocks

(1) Write file

#include<stdio.h>

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

Parameters: ptr: the address of the file data to be written

          size: The size of the block data written to the file content

          nmemb: The number of blocks written to the file

          stream: file pointer

           (Total size of data written to file: size*nmemb)

Return value: Success: the number of blocks actually written to the file, ie nmemb; failure: 0

(2) Read files

#include<stdio.h>

int fread( void* ptr,size_t _ElementSize,size_t _ElementCount,FILE* _stream);

Parameters: ptr: the address to store the read file data

          _ElementSize: block data size

          _ElementCount: the number of blocks read

          _stream: file pointer

Return value: Success: the number of content blocks actually successfully read. If this value is less than _ElementCount and greater than 0, it means that the end of the file has been read; failure: 0

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

void main()
{
    int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
    FILE* fp = fopen("D:/块数据.txt", "w");
    fwrite(arr, sizeof(int), 10, fp);
   // fwrite(arr, 20, 2, fp);//正确,只要数据大小是40即可
    fclose(fp);
}

result:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string>

void main()
{
    FILE* fp = fopen("D:/块数据.txt", "r");
    if (!fp)
    {
        return;
    }
    int arr[10] = { 0 };
    fread(&arr, 4, 10, fp);
    for (size_t i = 0; i < 10; i++)
    {
        printf("%d", arr[i]);//12345678910
    }
    fclose(fp);
}

Storage structure:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct student {
    std::string name;
    int age;
    std::string address;
};
void main()
{
    struct student stu[3] = {
                {"张三",20,"北京昌平"},
                {"李四",22,"北京朝阳"},
                {"王五",19,"北京海淀"}
            };
    FILE* fp = fopen("D:/存储结构体.txt", "w");
    for (size_t i = 0; i < 3; i++)
    {
        fwrite(&stu[i], sizeof(struct student), 1, fp);
    }
    fclose(fp);
}

Read the structure:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct student {
    char name[21];
    int age;
    char address[51];
};
void main()
{
    FILE* fp = fopen("D:/存储结构体.txt", "r");
    if (!fp)
    {
        return;
    }
    struct student* stu=(struct student*)malloc(sizeof(struct student)*3);
    for (size_t i = 0; i < 3; i++)
    {
        fread(&stu[i], sizeof(struct student), 1, fp);
        printf("%s\n", stu[i].name);
        printf("%d\n", stu[i].age);
        printf("%s\n", stu[i].address);

    }
    fclose(fp);
    free(stu);
}

 

Guess you like

Origin blog.csdn.net/weixin_39766005/article/details/109511993