Operator File

Operator File - Operate Files

Today I'm going to talk about Operator File, not much nonsense.



Viewpoint of this article

1. What is a file

2. Filename

3. File type

4. File Buffer

5. File Pointer

6. Opening and closing files

7. Order of reading and writing files

8. Random reading and writing of files

9. Decision on end of file


Let's get started!

1. What is a file?

Files are just files on our disks. When you see the attached pictures below, you can see the basic meaning of the file. (As to what obscure files are on your computer, I don't know anything.)

But in our programming, there are two kinds of files we usually talk about: program files; binary files

Program files:

Includes source files (suffix, c), target files (suffix.obj), executable files (suffix.exe)

If you don't have a roaring friend showing the file, you can refer to the picture above.





Extensions:
Source, target, executable contact:

Source files are saved as files with code written in assembly or advanced languages. Target files are compiled binary files that can be directly recognized by the cpu. Linking target files becomes executable files.

Source Code and Source File:

Source code (also known as source program)In modern programming languages, source code can appear as books or tapes, but the most common format is text files, which are typically designed to compile computer programs.

The ultimate goal of computer source code is to translate human readable text into binary instructions that the computer can execute. This process is called compilation and is accomplished by a compiler. In most cases, the source code is equal to the source file.

Reference Source: Baidu Encyclopedia-Source File




Data file:

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

This chapter discusses data files.

The input and output of data previously processed are all terminal-oriented, that is, the keyboard input data of the terminal, and the running results are displayed on the display.
In fact, sometimes we export information to disk and read data from disk to memory when needed. Here we process the files on disk.

Files are actually a medium, or a medium, for storing data.








2. Filename

A file must have a unique file identity for user identification and reference. The file name consists of three parts: file path + file name backbone + file suffix

For convenience, file identifiers are often referred to as file names







3. File type

Depending on how the data is organized, a data file is called a text file or binary file
 Data is stored in memory as binary, or binary if the output is not converted to external memory (hard disk)
If required on external memory (hard disk) ASCII Code, you need to convert it before storing to ASCII Files stored as characters are text files.


How is a data stored in memory?

 All characters follow ASCII Formal storage, numerical data can be used ASCII It can also be stored in binary form.

If there is integer 10000, if it is output to disk as ASCII code, it will take up to 5 bytes (one byte per character, treat 1 and 0 as one character)



Next let's validate it with an example

 We need to create one in this program project now test.txt Text file, run the program again, nothing can be done without this file program
#include<stdio.h>
int main()
{
	int a = 10000;
	FILE* pf = fopen("test.txt", "wb"); // Open a test.txt file,'wb'== write binary (write to file as binary)
	fwrite(&a/*Data from address a*/, 4/*Write 4byte*/, 1, pf);// fwrite writes the file, writes the contents of a in, &a means the data comes from the address of a, writes 4 byte s
	                                                        //Write a data like this (write a 4 byte data) and put it in a pf-maintained file
	fclose(pf);// Once you've finished writing, you can close the file
	pf = NULL; // Need to set to null pointer to protect file security.
	return 0;
}

After writing, run the program and the contents of the test.txt file have been changed. How can I observe it?
Solution Explorer -"Source File -" Backkey -"Select Add Existing Item -" Select the test.txt file we created, click Add





Successfully added, select the test.txt file - "backkey -" choose how to open - "select the binary compiler (click OK)
If you don't do this step, clicking directly to see is not effective





When you click on the test.txt file, you will find that the test.txt file displays the results of 10,000 in hexadecimal form (binary storage in memory, now just hexadecimal): 10,2700 (small-end storage mode)
That is, 0x 00 27 10






4. File Buffer

ANSIC Standard adoption "Buffered File System" Processing data files, the so-called buffer file system means that the system automatically opens up a block in memory for each file being used in the program "file buffer". 
Output data from memory to disk is sent to the in-memory buffer first, then to disk together when the buffer is full.
If data is read from disk to computer, data is read from disk files and entered into the memory buffer (full of buffers), then data is sent from the buffer to the program data area (program variables, etc.) one by one.
The size of the buffer is based on C Compile system-determined.







5. File Pointer

In a buffered file system, the key concept is the file type pointer, or simply the file pointer.

Each used file has a corresponding file information area in memory , Information about 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 whose type is declared and named by the system FILE.

FILE types in different C compilers do not contain exactly the same content, but they are much the same.

Appendix (vs2013):



Whenever a file is opened, a FILE structure is automatically created and filled with information based on the situation of the file so that the user does not have to care about the details.
Typically, this FILE structure is maintained through a FILE pointer, which makes it easier to use.
 
** FILE* pf;File Pointer pf. **

Defining a pf is a pointer to FILE-type data that points the pf to the file information area (a structure) of a file.
The file can be accessed/changed by the information in the file information area, that is, the file associated with it can be found by the file pointer.

As we access or modify the file information area of a file pointed to by the file pointer (FILE) (the structure changes as well)
That is, when a file is read and written, the size of the file, the instructions for the current file, and so on, all change.





6. Opening and closing files

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

When you write a program, when you open a file, a pointer returning FILE* points to the file (the information area of the file), which is equivalent to establishing a relationship between the pointer and the file.
ANSIC specifies that the fopen function is used to open the file and fclose to close it.

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

// int close( FILE* stream );


Mode:

How to use filesMeaningIf 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" (append)Add data to the end of a text fileerror
"rb" (read-only)To enter data, open a binary fileerror
"wb" (write-only)To output data, open a binary fileCreate a new file
"ab" (append)Add data to the end of a binary fileerror
"r+" (read and write)Open a text file for reading and writingerror
"w+" (read and write)Suggest a new file for reading and writingCreate a new file
"a+" (read and write)Open a file and read and write at the endCreate a new file
"rb+" (read and write)Open a binary file for reading and writingerror
"wb+" (read and write)Create a new binary for reading and writingCreate a new file
"ab+" (read and write)Open a binary file for reading and writing at the end of the fileCreate a new file




Let's get started!

Program 1 (fopen function):

#include<stdio.h>
int main()
{
	//Open the file (test.txt)

	// Relative Path Writing
	fopen("test.txt", "wb");  	//  .Represents the current path

	fopen("../test,txt", "wb");
	//  ..Indicates the upper path of the current path, such as file 1 containing the program, and file 2 containing file 1 and test.txt
	

	fopen("../../test.txt", "wb");// Upper path of current path

	//Writing of absolute paths
	fopen("G:\\program\\operator file\\operator file\\test.txt", "wb");
	//  The double slash \ here is designed to make \ simply a slash. Because \ is combined with other characters, it forms an escape character
	return 0;

}



Program 2 (fclose function):

#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
	//Open the file (test.txt)

	// Relative Path Writing
	FILE*pf = fopen("test.txt", "r"); // When you write a program, when you open a file, you return a FILE* pointer to the file (the information area of the file)
	// That is, we need a FILE type pointer to receive
	//	However, fopen has the possibility of failure to open. Failing to open fopen will return a null pointer

	if (!pf)// If pf is NULL == 0, false, inverse true, execute if statement
	{
		printf("%s\n",strerror(errno));//Output Error Information
		return 0;// Program End
	}
	// Go here to show success in opening
	// Read file "r" (read-only)
	// Close File
	fclose(pf);// Similar to the free function, free frees up dynamic space (which is returned to the operating system) and closes files when fclose functions
	pf = NULL;// fclose protects files, free protects the system
	return 0;

}



Program 3 (w open mode):

#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
	//Open the file (test.txt)

	// Relative Path Writing
	FILE*pf = fopen("test.txt", "w"); // When you write a program, when you open a file, you return a FILE* pointer to the file (the information area of the file)
	// That is, we need a FILE type pointer to receive
	//	Fopen has the possibility of opening failure. Failing to open fopen will return a null pointer
	// Open mode "w" creates a file when the specified file does not exist and returns its address. If the file exists and has content, run the program to create a new file, and the contents of the old file are destroyed
	
To put it plainly, if your current file does not contain test When the file is opened in "w"(Write-only),It automatically generates a test Text files

	// So no if statement will be executed to show an error
	if (!pf)
	{
		printf("%s\n", strerror(errno));
		return 0;
	}
	// Go here to show success in opening
	// Read File "r"
	// Close File
	fclose(pf);
	pf = NULL;
	return 0;

}






7. Order of reading and writing files

functionFunction nameApplicable to
Character input functionfgetcAll input streams
Character Output FunctionfputcAll Output Streams
Text input functiongetsAll input streams
Text Output FunctionfputsAll Output Streams
scanffscanfAll input streams
printffprintfAll Output Streams
Binary Inputfreadfile
Binary Outputfwritefile




Character output function fputc: int fputc (int c, FILE *stream);

Before running the program, ensure that test. txt File content is empty, so we can easily observe the phenomenon
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
	FILE* pf = fopen("test.txt", "w");
	if (!pf)
	{
		printf("%s\n",strerror(errno));
		return 0;
	}
	// Write File
	fputc('b', pf);// Output a character to file to leave
	fputc('i', pf);
	fputc('t', pf);
  // 
  Close File
	fclose(pf);
	pf = NULL;
	return 0;
}

Appendix:





Character input function fgetc

#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (!pf)
	{
		printf("%s\n", strerror(errno));
		return 0;
	}
	// read file
	printf("%c ", fgetc(pf));// b
	printf("%c ", fgetc(pf));// i
	printf("%c ", fgetc(pf));// t
	//Close File
	fclose(pf);
	pf = NULL;
	return 0;
}

Appendix:






So can we make it look like it used to, keyboard input, screen display?

The answer is yes. But before we can do that, we need to understand

Input from keyboard 
Output to Screen
 keyboard & Screens are external devices

Call the keyboard a standard input device - stdin
 Call the screen a standard output device - stdout
 Is a program that opens two stream devices by default

In addition, as long as the program runs, it opens three streams by default
stdin
stdout
stderr: standard output(equipment)The process will get input data from the standard input file, output normal output data to the standard output file, and send error information to the standard error file. C In, the program remains open when it executes.

 All three are open by default, and all three streams are of type FILE* Of



Let's get to know it through the program

#include<stdio.h>
int main()
{
	int ch = fgetc(stdin);// Input from keyboard, why use int ch, MSDN view
	fputc(ch,stdout);// Output on screen
	return 0;

}





Text input function fgets: char *fgets (char *string, int n, FILE *stream);



 I'm already ahead of time at test.txt Write
 bit
 HELLO

#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
	char buf[1024] = { 0 };// Create an array to store strings
	FILE* pf = fopen("test.txt", "r");
	if (!pf)
	{
		printf("%s\n", strerror(errno));
		return 0;
	}
	// read file
	fgets(buf,1024,pf);// Store the string in the file information area that pf points to in the buf array
	//printf("%s\n",buf);// bit
	                   //
	                   // Press any key to continue...
	                   //You'll find a space in the middle
	                   
	// Print a row of data bit\n
	printf("%s",buf);  // Remove'\n'==printf(buf);  
	//puts(buff)//rule 
	                   // bit
	                   // Press any key to continue...
	                   // Explain that buf actually has a line break inside it (this should be noted)

	// Print the second line of data HELLO, HELLO does not have \n because \n only has one
	fgets(buf, 1024, pf);
	printf("%s", buf);
	// puts(buf)

	// If you use puts, you will find that every time you print, puts will naturally wrap after printing 

	fclose(pf);
	pf = NULL;
	return 0;
}






Text output function fputs: fputs: int fputs (const char *string, FILE *stream);

#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
	char buf[1024] = { 0 };
	FILE* pf = fopen("test.txt", "w");
	if (!pf)
	{
		printf("%s\n", strerror(errno));
		return 0;
	}
	// Write File
	fputs("hello", pf);// Write hello into pf
	fputs("world", pf);
	                  // Click on the file to see the effect (helloword)
	                  // fputs don't automatically wrap lines for you. To wrap lines, we need to append\n to the string
	fputs("\n",pf);
	fputs("hello\n", pf);// Write hello into pf
	fputs("world\n", pf);

	fclose(pf);
	pf = NULL;
	return 0;
}




Text Output Function fputs (Standard I/O Form)

#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{   // Read a line of text from the keyboard
	char buf[1024] = { 0 };
	fgets(buf,1024,stdin);// Read from standard input
	fputs(buf,stdout);// Output to Standard Output Stream (Screen)

	// This is equivalent to gets(buf);
	//               puts(buf);
	return 0;
}





Format Output Function fprintf All Input Streams

                         int printf(const char *format[, argument]...);// For Standard Output Stream
int fprintf(FILE *stream, const char *format[, argument]...);// All Output Streams

You will find that there is a stream (pointer to FILE structure) between fprintf and printf.

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

struct s
{
	int n;
	float score;
	char arr[10];
};

int main()
{                       // No f, default to double type
	struct s s = { 100, 3.14f, "bit" };
	FILE* pf = fopen("test.txt", "w");
	if (!pf)
	{
		printf("%s\n", strerror(errno));
		return 0;
	}
	// Write a file in formatted form
	fprintf(pf, "%d %f %s", s.n, s.score, s.arr);// fprintf is simply more streams than printf (pointer pf of FILE structure)
Save structure member values in formatted data pf Point to File Information Area (File)

	fclose(pf);
	pf = NULL;
	return 0;
}







Formatted input function fscanf applies to all output streams (standards and files)

                   int scanf(const char *format[, argument]...);
    int fscanf(FILE *stream, const char *format[, argument]...);

Like fprintf, let's not say much here. Look directly at the program

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

struct s
{
	int n;
	float score;
	char arr[10];
};

int main()
{                 
	struct s s = { 0 };
	FILE* pf = fopen("test.txt", "r");
	if (!pf)
	{
		printf("%s\n", strerror(errno));
		return 0;
	}
	// Formatted input data
	fscanf(pf, "%d %f %s", &(s.n), &(s.score), s.arr);// Take three data from pf and assign structure member variables in%d%f%s format
	printf("%d %f %s\n", s.n, s.score, s.arr);// Print structure member variables

	fclose(pf);
	pf = NULL;
	return 0;

}






Let's look at their two standard output inputs (fprintf and fscanf).

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

struct s
{
	int n;
	float score;
	char arr[10];
};

int main()
{                       
	struct s s = { 0 };
	fscanf(stdin, "%d %f %s", &(s.n), &(s.score), s.arr);// Enter three data from stdin (keyboard) and assign structure member variables in%d%f%s format
	fprintf(stdout, "%d %.2f %s", s.n, s.score, s.arr);// Print structure member variables


	return 0;

}







Compare a set of functions (in fact, they convert, write in, and take out):

fscanf / sscanf

fprintf / sprintf

scanf / printf is a formatted input / output statement for standard input stream / standard output stream

fscanf / fprintf is a formatted input/output statement for all output/input streams


sscanf / sprintf, before comparing this pair, let me look at these two functions

sscanf function: Read formatted data from a string.Take formatted data out of a string
int sscanf(const char *buffer, const char format[, argument] ...);
One more const char buffer than scanf

sprintf function: Write formatted data to a string.Write formatted data to a string
int sprintf(char *buffer, const char format[, argument] ...);
One more const char buffer than printf

#include<stdio.h>

struct s
{
	int n;
	float score;
	char arr[10];

};

int main()
{
	struct s s = { 100, 3.14f, "abcdef" };
	struct s tmp = { 0 };// Create a structure variable to store the sscanf function to convert strings to formatted data
	char buf[1024] = { 0 };// See an array of characters used to store sprintf functions to write formatted data as string type data

// Write in before you read, nothing to read

	// Formatted data conversion string stored in buf
	sprintf(buf, "%d %f %s", s.n, s.score, s.arr);// sprintf converts the data here to string type
	//printf("%s\n", buf);// 100  3.1400 abedef
	                  //Here 100 3.14 abcdefs are all converted to strings

	//Read formatted data from buf to tmp
	sscanf(buf, "%d %f %s", &(tmp.n), &(tmp.score), tmp.arr);//Convert the data in buf back to their original type
	printf("%d %f %s", tmp.n, tmp.score, tmp.arr);
	return 0;
}


After the above explanations, I believe you have almost understood them. Let's analyze the use of these two functions.

sscanf / sprintf

// sscanf reads formatted data from a string (converts the data in the string to formatted data and assigns it to other variables)
// sprintf is the output (stored) of formatted data into a string (converted (or written) into a string that is stored in a space (file) or to the (printed) external (screen).






Binary output fwrite: size_t fwrite (const void *buffer, size_t size, size_t count, FILE *stream);

buffer
Pointer to data to be written Pointer to write data

size
Item size in bytes  Size units of elements  byte
  
count
Maximum number of items to be written  Maximum number of elements to be written

stream
Pointer to FILE structure point FILE Pointer to structure 


The procedure is as follows:

#include<stdio.h>

struct s
{
	char name[20];
	int age;
	double score;// Score/score
};

int main()
{
	struct s s = { "Zhang San", 20, 55.6 }; 
	FILE* pf = fopen("test.txt", "wb");
	if (!pf)
	{
		return 0;
	}
	//  Write files in binary form
	fwrite(&s, sizeof(struct s), 1, pf);
	// The contents of test,txt are: Zhang San swallowing hot K@
	
	//Zhang San's binary, ASCII form of storage are the same, other is not, so the following content can not be read, because the data is written in binary

	// Close File
	fclose(pf);
	pf = NULL;
	return 0;
}



Binary input fread: size_t FREAD (void *buffer, size_t size, size_t count, FILE *stream);

buffer
Storage location for data   Location to store data

size
Item size in bytes  Element size in bytes

count
Maximum number of items to be read Maximum number of elements read

stream
Pointer to FILE structure point FILE Pointer to structure


The procedure is as follows:

#include<stdio.h>

struct s
{
	char name[20];
	int age;
	double score;// Score/score
};

int main()
{

	struct s tmp = { 0 };
	FILE* pf = fopen("test.txt", "rb");
	if (!pf)
	{
		return 0;
	}
	//  Read files in binary form
	fread(&tmp, sizeof(struct s), 1, pf);// Take a structure of sizeof(struct s) size from pf and assign its value to the structure variable tmp

	printf("%s %d %lf\n", tmp.name,tmp.age, tmp.score);

	// Close File
	fclose(pf);
	pf = NULL;
	return 0;
}







8. Random reading and writing of files

When it comes to random reading and writing, there's a function involved  fseek

Now let's take a look at the fseed function

fseek Function:
Moves the file pointer to a specified location.  Move file pointer to specified location

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

stream
Pointer to FILE structure    FILE Pointer to structure

offset
Number of bytes from origin  Bytes from origin (offset)

origin
Initial position     Start position (current position of file pointer)   

origin is written in the following ways:

SEEK_CUR
Current position of file pointer  Current position of file pointer

SEEK_END
End of file  End of file

SEEK_SET
Beginning of file File Start Location


Procedural Practice:

#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
	FILE* pf = fopen("test.txt", "r");// The content of test.txt is abcdef
	if (!pf)
	{
		printf("%s\n", strerror(errno));
		return 0;
	}
	//  1. Locate file pointer: Locate file pointer according to its position and offset
	fseek(pf, 4, SEEK_CUR);// From the current location of the file, offset 4, point to e

	//fseek(pf, -2, SEEK_END);//To get e from the end of the file, the offset should be -2 (the file pointer points to the back of f, which is where the offset is 0)

	//  2. Read Files
	int ch = fgetc(pf);
	printf("%c\n", ch);// e

	//  3. Close the file
	fclose(pf);
	pf = NULL;
	return 0;
}






ftell function: long ftell(FILE *stream);

Gets the current position of a file pointer.Get the current location of the file pointer
(Returns the offset of the file pointer from the starting position)

Procedure 1:

#include<stdio.h>
#include<errno.h>
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (!pf)
	{
		printf("%s\n", strerror(errno));
		return 0;
	}
	// Returns the current position of the file pointer
	int pos = ftell(pf);//File pointers are not handled by fseek, so the file points to the starting location (offset 0)

	printf("%d\n", pos);//    0

	fclose(pf);
	pf = NULL;
	return 0;
}


Procedure 2:

#include<stdio.h>
#include<errno.h>
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (!pf)
	{
		printf("%s\n", strerror(errno));
		return 0;
	}
	// 1. Locate file pointer
	fseek(pf, 4, SEEK_CUR);

	// Returns the current position of the file pointer
	int pos = ftell(pf);// Since fsek was already present, the file pointer points to an offset of 4
	printf("%d\n", pos);//    4

	fclose(pf);
	pf = NULL;
	return 0;
}


Procedure 3:

#include<stdio.h>
#include<errno.h>
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (!pf)
	{
		printf("%s\n", strerror(errno));
		return 0;
	}
	// 1. Locate file pointer
	fseek(pf, 4, SEEK_CUR);// At this point, the file location points to the offset of 4 and to e
	int ch  = fgetc(pf);// fgetc reads e, the file pointer pf points to the next location, offset 5

	// Returns the current position of the file pointer
	int pos = ftell(pf);// Because fgets was done once before, the file pointer no longer points to an offset of 4, but to an offset of 5
	 // pos == 5

	printf("%c\n", ch); //    e
	printf("%d\n", pos);//    5

	fclose(pf);
	pf = NULL;
	return 0;
}






rewind function: returns the file pointer to its starting position


Procedural Practice:

test.txt content abcdef
#include<stdio.h>
#include<errno.h>
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (!pf)
	{
		printf("%s\n", strerror(errno));
		return 0;
	}
	// 1. Locate file pointer
	fseek(pf, 4, SEEK_CUR);// At this point, the file pointer points to the offset of 4, which is e

	//This returns the file pointer to its starting position
	rewind(pf);

	// fgetc should read a
	int ch = fgetc(pf);


	printf("%c\n", ch); //    a
	fclose(pf);
	pf = NULL;
	return 0;
}







9. Decision on end of file

Feof function: int feof(FILE *stream);


The feof function used incorrectly:

#include<stdio.h>
int main()
{
	//EOF(-1) - end of file end flag
	// So feof is used to judge the end of the file, it's not

	FILE* pf = fopen("test.txt","r"); //  Empty the contents of the test.txt file before executing the program
	                                 // Because if there's nothing in the file, the first fgetc read it was EOF
	if (!pf)
	{
		return 0;
	}
	int ch = fgetc(pf);
	printf("%d\n", ch);// -1 == EOF, indicating that an EOF is placed at the end of the file

	fclose(pf);
	pf = NULL;


	return 0;
}


Keep in mind that during file reading, the return value of the feof function cannot be used directly to determine whether the file is over. Instead, it is applied to the end of the current file reading to determine whether the end of the read failed or encountered the end of the file (that is, we already know that the file reading has ended, but what caused the end of the file)

1. End of text file reading, determine whether the returner is EOF (fgetc), or NULL (fgets)

For example:

  1. fgetc determines if it is EOF
  2. fgets to determine if the return value is NULL

2. Binary file end-of-read judgment to determine if the return value is less than the actual number of reads

For example, fread determines if the return value is less than the actual number to read


Procedural Practice:

#include<stdio.h>
#include<stdlib.h>
int main()
{
	int c;// Return value to receive fgetc
	FILE* pf = fopen("test.txt", "r");
	if (!pf)// So you must run the if statement
	{
		perror("File opening failed");// Print the error message and let me explain it at the end
		return EXIT_FAILURE/*Represents -1, indicating the status value of the file open failure*/;
	}// If the file you want to open does not exist, the program ends printing error messages here
	
	// Open Successfully
	while ((c = fgetc(pf)) != EOF) // Read one, print one, and if you read'EOF == -1', jump out of the while loop statement
	{ // Standard I/O Read File Loop 
		putchar(c);
	}
	
	//Decide when it ends
	if (ferror(pf))// If there is no error with the stream (pf), ferror returns 0 (read successful), in addition to a non-zero number (read failed)
	{ 
		puts("I/O error when reading");// The test.txt file ended reading abnormally while reading and writing
		// Here is read successfully, so if statement is not executed
	}
	
	else if (feof(pf))// feof determines if pf ends up with (read to) EOF
		// The value returned by feof is non-zero, indicating that it ended because it encountered EOF
		// Returns 0 if the current location is not the end of the file. No information is returned
	{
		puts("End of file reached successfully");// Because the file was read to end with EOF, a non-zero value was returned
		// Executes the statement and prints the contents of the statement, indicating that the file was read and ended normally when it encountered EOF.
	}
	fclose(pf);
	pf = NULL; 
	return 0;
}







Binary files are similar to text files, that is, the difference between reading them

while ((size_t c = fread(void *buffer, size_t size, size_t count, FILE *stream)) >=1)

fread returns the number of complete items actually read, which may be less than count if an error occurs or if a file ends before counts are reached. Use the feof or ferror function to distinguish between read errors and end-of-file conditions. If size or count is 0, fread returns 0 and the buffer content remains the same.

That is, if count is 0, it must indicate that the read is complete. If the read ends abnormally, count will be greater than 0, indicating that there is still data left to read.







Finally, let's look at the perror function

Let's start with an example:

#include<stdio.h>
#Include <errno.h>//error code library
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (!pf)
	{
		//Printf ('%s\n', strError (errno)); //StrError - Returns a string of error information corresponding to the error code
		return 0;    // The strerror function needs to be accompanied by the errno.h header file to print error information
	}
	return 0;
}





Let's look at the perror function again

#include<stdio.h>
int main()
{
	FILE* pf = fopen("test2.txt", "r");// The test2.txt file does not exist
	if (!pf)// So it must have failed to open, execute if statement
	{
		perror("hehe");// Print hehe: No such file or directory on screen
		               // It's easy to see that hehe is the name of the problem here
		              // perror does not need strerror functions (converting error code information) and errno.h (providing error code) header files, and printf printing functions (printing error information)
		              // Print error messages directly
		return 0;
	}
	// read file
	// Close File
	fclose(pf);
	pf = NULL;
	return 0;
}

perror can actually be seen as a combination of strerror and printf, as well as errno.h (which automatically gets the error code, passes it to the address of the error message, and prints it). The only disadvantage is that if you use it, it will print the error message, not not not (arbitrarily). The strerror function controls not to print the error message.(as long as you don't use print functions (e.g., printf, puts, etc.).


This concludes the article.

Tags: C

Posted on Fri, 17 Sep 2021 00:42:08 -0400 by Darrel