C language -- document (high level Part 28)

 

File pointer

Definition:

FILE * pointer variable name;

For example:

      FILE *fp1,*fp2;

Two pointers to the file are defined at a time

 

File operation mode

※ text mode

Text mode stores data in files in ASCII code mode. The "text file" in our computer is a typical file stored in text mode.

※ binary mode

Non text data such as music and graphics are more suitable for binary storage

 

Open file

Format:

File * fopen (file name, file usage);

For example:

        FILE *fp;

        fp=fopen("file_a","r");

 

Usage list:

※ "r", the text is read-only

※ "rb", binary read-only

※ "w", the text is written only

※ "wb", binary write only

※ "a", text added

※ "ab", binary addition

 

      ※ r+,w+,a+,rb+,wb+,ab+

For files opened with a plus sign, reading and writing are allowed, and other operations are the same as those in the previous 6 items.

 

Errors often occur when opening a file. For example, the file does not exist at all. The following methods can be used to check:

      if((fp=fopen("file_a","r"))= =NULL)

      {

        printf("Cannot open this file\n");

        exit(0); /* Exit the program*/

      }

 

Close file

Format:

Fclose (file pointer);

 

Reading and writing of text files

Write:

Putc (character, file pointer);

Read:

Char Getc (file pointer);

To determine whether the end of the file:

      EOF

Because ASCII characters have no negative numbers, EOF is defined as - 1 in C language. When reading a function from a file, the end of the file is marked when - 1 or EOF is encountered.

 

Procedure 1

Writes the string "Hello" to a text file

// 28-1 String hello Write text file.c

#include <stdio.h>

main()
{
    FILE *fp;   //Define file pointer
    char str[20] = "hello";  //Defines the string to write
    char *pc = str;  //Pointer to character name
    fp = fopen("myfile.txt", "a");   //Open file
    if (fp == NULL)  //If it is fp Empty
    { 
        printf("Error opening file!\n");
        exit(0);    //System exit
    }

    while (*pc != '\0')
    {
        putc(*pc, fp);   //Write characters to file
        pc++;
    }

    fclose(fp);  //Close file


}

Procedure 2

Read the contents of the text file in program 1

// 28-2 read myfile Contents of Chinese text file.c

#include <stdio.h>

main()
{
    FILE *fp; //Define file pointer
    char str[20]; //Define a character to receive the characters in the file
    char *pc = str; //Pointer to character name
    fp = fopen("myfile.txt", "r");  //read myfile file

    if (fp == NULL)
    {
        printf("Failed to open file!");
        exit(0);
    }

    //Cycle through the characters in the file until the EOF end

    *pc = getc(fp);   //This sentence is for the following while Judge whether it is during the cycle EOF
    while (*pc != EOF)
    {
        pc++;
        *pc = getc(fp);
    }

    *pc = '\0';   //Assignment Terminator
    fclose(fp);
    printf("%s\n", str);

}

In addition to these two functions, there are several functions that can read data in batch:

Fscanf (file pointer, format control string, output table column);

For example:

      fscanf(fp,"%d %d",&a,&b);

Fprintf (file pointer, format control string, output table column);

For example:

      fprintf(fp,"%d %d",a,b);

 

 

Fgets (array name, number of characters, file pointer);

For example:

      fgets(str,n,fp);

Fputs (array name, file pointer);

For example:

      fputs(str,fp);

 

※ these functions are somewhat similar to the functions we usually use when operating strings, except that fgets adds a "number of characters" parameter.

 

Reading and writing of binary files

Binary files can store any type of data, there may be negative numbers, so we have to use other methods to judge the end of the file.

Function for judging the end of a file:

Int feof (file pointer);

When the end of the file is encountered, the return value is 1, otherwise it is 0.

 

Write:

Fwrite (first memory address, memory size, number of memory, file pointer);

Read:

FREAD (first memory address, memory size, number of memory, file pointer);

 

Procedure 3

Read / write binary file

// 28-3 Read / write binary file.c

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


//Define student structure
struct student
{
    char name[10];   //name
    int age;         //Age
};

main()
{
    FILE *fp; 
    struct student stu1, stu2;  //Define two student structure variables

    stu1.age = 17;    //Student 1 age assignment
    strcpy(stu1.name, "Zhang santuzi");  //String assignment requires function assignment


    //Write structure variable to file
    fp = fopen("temp.dat", "wb"); 
    //fwrite(First memory address, memory size, number of memory, file pointer);
    fwrite(&stu1, sizeof(struct student), 1, fp);
    fclose(fp);


    //Read file to stu2
    fp = fopen("temp.dat", "rb");
    //fwrite(First memory address, memory size, number of memory, file pointer);
    fread(&stu2, sizeof(struct student), 1, fp);
    fclose(fp);

    printf("%s\n%d\n", stu2.name, stu2.age);


}
// 28-4 The difference between binary file and text file.c
//

#include <stdio.h>

main()
{
    FILE *fp;
    int i = 7000;

    //Binary file
/*    fp = fopen("temp.txt", "wb");   //The file created by binary opening is garbled
    fwrite(&i, sizeof(int), 1, fp);
*/


    //text file
    fp = fopen("temp1.txt", "w");
    fprintf(fp,"%d",i);
    fclose(fp);
}

 

Practice

Please call the fputs function to output 5 strings to the file (note that each string is separated by carriage return); Then read the five strings from this file and put them in a string array; Finally, the string in the string array is output to the terminal screen to verify whether all operations are correct.

 

/*28-5 Exercise. c
 Please call the fputs function to output 5 strings to the file (note that each character is separated by carriage return);
Then read the five strings from this file and put them in a string array; Finally, put the string in the array
 The string is output to the terminal screen to verify that all operations are correct.
*/
#include <stdio.h>
main()
{
    char strout[5][10] = { "shout","anything","tent","mouse","ear" };  //Files written
    char strin[5][10];
    FILE *fp;

    //write file
    if ((fp = fopen("28.txt", "w")) == NULL)
    {
        printf("File open error!");
        exit(0);
    }

    for (int i = 0; i < 5; i++)
    {
        fputs(strout[i],fp);
        putc('\n',fp);
    }

    fclose(fp);


    //read file
    if ((fp = fopen("28.txt","r")) == NULL) 
    {
        printf("File open error!");
        exit(0);
    }

    for (int i = 0; i < 5; i++)
    {
        //fscanf(field name pointer, Format control string, Output table column);
        fscanf(fp,"%s",strin[i]);
        printf("%s\n", strin[i]);
    }
    
}

 

Keywords: C

Added by Shifty Geezer on Wed, 03 Nov 2021 02:55:57 +0200