[C language intensive instruction] C language file operation

Posted by SpectralDesign.Net on Fri, 04 Mar 2022 15:56:08 +0100

catalogue

1. Type of document

1.1 procedure documents

1.2 data files

1.3 file name

2. Opening and closing of files

2.1 document pointer

2.2 opening and closing of documents

3. Sequential reading and writing of documents

4. Random reading and writing of documents

4.1 fseek

4.2 ftell

4.3 rewind

5. Text files and binary files

6. Determination of the end of file reading

7. File buffer

1. Type of document

Files on disk are files. In programming, we generally talk about two kinds of files: program files and data files (classified from the perspective of file function).

1.1 procedure documents

Including source program files (suffix. c), object files (suffix. obj in windows Environment), and executable programs (suffix. exe in windows Environment)

1.2 data files

The content of the file is not necessarily the program, but the data read and written when the program is running, such as the file from which the program needs to read data or the file that outputs the content.

File operations mentioned in this article refer to data files.

1.3 file name

A file has a unique file ID for user identification and reference. For convenience, the file ID is often referred to as the file name.

The file name includes three parts: file path + file name trunk + file suffix. For example: C: \ code \ test txt

2. Opening and closing of files

2.1 document pointer

In the buffered file system, the key concept is "file type pointer", which is referred to as "file pointer".

  • Each used FILE opens up a corresponding FILE information area in the memory to store the relevant information of the FILE (such as the name of the FILE, the status of the FILE, the current location of the FILE, etc.). This information is stored in a structure variable. The structure type is declared by the system and named FILE
  • Whenever a FILE is opened, the system will automatically create a variable of FILE structure and fill in the information according to the situation of the FILE. Generally, the variables of this FILE structure are maintained through a FILE pointer, which is more convenient to use.

FILE* pf; / / create a file pointer variable of file *

Definition PF is a pointer variable pointing to data of type FILE. You can make pf point to the FILE information area of a FILE (which is a structure variable). The FILE can be accessed through the information in the FILE information area. That is, the FILE associated with it can be found through the FILE pointer variable.

2.2 opening and closing of documents

The file should be opened before reading and writing, and closed after use.

When writing a program, when opening a FILE, a pointer variable of FILE * will be returned to point to the FILE, which is equivalent to establishing the relationship between the pointer and the FILE.

#include <errno.h>
#include <stdio.h>
#include <string.h>
int main()
{
	//Open file
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
		//printf("failed to open file \ n");
		printf("%s\n", strerror(errno));
		return 0;
	}
	//Close file
	fclose(pf);
	pf = NULL;

	return 0;
}

Opening method type:

File usagemeaningIf the specified file does not exist
"r" (read only)To enter data, open an existing text fileerror
"w" (write only)To output data, open a text fileCreate a new file
"a" (added)Add data to the end of a text fileCreate a new file
"rb" (read only)To enter data, open a binary fileerror
"wb" (write only)To output data, open a binary fileCreate a new file
"ab" (additional)Add data to the end of a binary fileerror
"r +" (read / write)To read and write, open a text fileerror
"w +" (read / write)For reading and writing, suggest a new fileCreate a new file
"a +" (read-write)Open a file and read and write at the end of the fileCreate a new file
"rb +" (read and write)Open a binary file for reading and writingerror
"wb +" (read / write)Create a new binary file for reading and writingCreate a new file
"ab +" (read and write)Open a binary file and read and write at the end of the fileCreate a new file

3. Sequential reading and writing of documents

functionFunction nameApply to
Character input functionfgetcAll input streams
Character output functionfputcAll output streams
Text line input functionfgetsAll input streams
Text line output functionfputsAll output streams
Format input functionfscanfAll input streams
Format output functionfprintfAll output streams
Binary inputfreadfile
Binary outputfwritefile

Write file:

#include <errno.h>
#include <stdio.h>
#include <string.h>
int main()
{
	//Open file
	FILE* pf = fopen("test.txt", "w");
	if (pf == NULL)
	{
		//printf("failed to open file \ n");
		printf("%s\n", strerror(errno));
		return 0;
	}
	//Write file
	char ch = 0;
	for (ch = 'a', ch <= 'z'; c++)
	{
		fputc(ch, pf);
        //fputc(ch, stdout) / / output to the screen
	}
	//Close file
	fclose(pf);
	pf = NULL;

	return 0;
}

Read file:

int ch = 0;    //If it is a char type, there is no EOF (- 1) in it
while ((ch = fgetc(pf)) != EOF)
{
    printf("%c ", ch);
}

Output / read in by text line: (note the file opening mode)

//Output by text line
fputs("hello world\n", fp);
//Read in by text line
char buf[1000] = { 0 };
fgets(buf, 1000, fp);

4. Random reading and writing of documents

4.1 fseek

Locate the file pointer according to the position and offset of the file pointer.

int fseek ( FILE * stream, long int offset, int origin );

/* fseek example */
#include <stdio.h>
int main()
{
	FILE* pFile;
	pFile = fopen("example.txt", "wb");
	fputs("This is an apple.", pFile);
	fseek(pFile, 9, SEEK_SET);
	fputs(" sam", pFile);
	fclose(pFile);
	return 0;
}

4.2 ftell

Returns the offset of the file pointer from the starting position.

long int ftell ( FILE * stream );

/* ftell example : getting size of a file */
#include <stdio.h>
int main()
{
    FILE* pFile;
    long size;
    pFile = fopen("myfile.txt", "rb");
    if (pFile == NULL) perror("Error opening file");
    else
    {
        fseek(pFile, 0, SEEK_END);   // non-portable
        size = ftell(pFile);
        fclose(pFile);
        printf("Size of myfile.txt: %ld bytes.\n", size);
    }
    return 0;
}

4.3 rewind

Return the position of the file pointer to the starting position of the file.

void rewind ( FILE * stream );

/* rewind example */
#include <stdio.h>
int main()
{
    int n;
    FILE* pFile;
    char buffer[27];
    pFile = fopen("myfile.txt", "w+");
    for (n = 'A'; n <= 'Z'; n++)
        fputc(n, pFile);
    rewind(pFile);
    fread(buffer, 1, 26, pFile);
    fclose(pFile);
    buffer[26] = '\0';
    puts(buffer);
    return 0;
}

5. Text files and binary files

According to the organization form of data, data files are called text files or binary files.

  • Data is stored in binary form in memory. If it is output to external memory without conversion, it is a binary file.
  • If it is required to store in the form of ASCII code on external memory, it needs to be converted before storage. The file stored in the form of ASCII characters is a text file.

6. Determination of the end of file reading

  1. Whether the reading of the text file is finished, judge whether the return value of fgetc is EOF (fgetc), or whether the return value of fgets is NULL (fgets)
  2. Judge whether the return value is less than the actual number to be read after reading the binary file. (fread determines whether the return value is less than the number of actual reads.)

feof function is to judge whether the reading fails or the end of the file is encountered when the file reading ends.

Examples of text files:

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    int c; // Note: int, not char, requires EOF processing
    FILE* fp = fopen("test.txt", "r");
    if (!fp) {
        perror("File opening failed");
        return EXIT_FAILURE;
    }
    //fgetc will return EOF when reading fails or when the file ends
    while ((c = fgetc(fp)) != EOF) // Standard C I/O read file cycle
    {
        putchar(c);
    }
    //Judge why it ended
    if (ferror(fp))
        puts("I/O error when reading");
    else if (feof(fp))
        puts("End of file reached successfully");
    fclose(fp);
}

Examples of binary files:

#include <stdio.h>
enum { SIZE = 5 };
int main(void)
{
    double a[SIZE] = {1.,2.,3.,4.,5.};
    FILE *fp = fopen("test.bin", "wb"); // Binary mode must be used
    fwrite(a, sizeof *a, SIZE, fp); // Write an array of double
    fclose(fp);
    double b[SIZE];
    fp = fopen("test.bin","rb");
    size_t ret_code = fread(b, sizeof *b, SIZE, fp); // Read the array of double
    if(ret_code == SIZE) {
        puts("Array read successfully, contents: ");
        for(int n = 0; n < SIZE; ++n) printf("%f ", b[n]);
        putchar('\n');
   } else { // error handling
       if (feof(fp))
          printf("Error reading test.bin: unexpected end of file\n");
       else if (ferror(fp)) {
           perror("Error reading test.bin");
       }
   }
    fclose(fp);
}

7. File buffer

ANSIC standard uses "buffer file system" to process data files. The so-called buffer file system refers to that the system automatically opens up a "file buffer" for each file being used in the program in memory. Data output from memory to disk will be sent to the buffer in memory first, and then sent to disk together after the buffer is filled. If you read data from the disk to the computer, read the data from the disk file, input it into the memory buffer (fill the buffer), and then send the data from the buffer to the program data area (program variables, etc.) one by one. The size of the buffer is determined by the C compilation system.

#include <stdio.h>
#include <windows.h>
//VS2013 WIN10 environment test
int main()
{
	FILE* pf = fopen("test.txt", "w");
	fputs("abcdef", pf);//Put the code in the output buffer first
	printf("Sleep for 10 seconds-The data has been written. Open it test.txt File, no content found in the file\n");
	Sleep(10000);
	printf("refresh buffer \n");
	fflush(pf);//When the buffer is refreshed, the data of the output buffer is written to the file (disk)
	//Note: fflush cannot be used on higher version VS
	printf("Sleep for another 10 seconds-At this point, open again test.txt File, the file has content\n");
	Sleep(10000);
	fclose(pf);
	//Note: fclose also flushes the buffer when closing the file
	pf = NULL;
	return 0;
}

Conclusion: because of the existence of buffer, C language needs to refresh the buffer or close the file at the end of file operation. If not, it may cause problems in reading and writing files.

Topics: C Back-end