1, the introduction
File is an important concept in programming. To store data to the external media, you must also create a file (identified by the file name) before you can output data to it. “File” generally refers to a collection of data stored on external media. A batch of files is stored as data on an external medium, such as a disk. Operating system was the data file management, that is to say, if you want to find the data on the external medium, must find the file specified by filename, then read the data from the file and run the program, often need to some data (running the final result or intermediate data) output to disk to store up, Input from disk to computer memory as needed later. This requires disk files.
In the operating system, different hardware devices are treated as one file in order to unify the operation of various hardware devices and simplify the interface. Operations on these files are the same as operations on ordinary files on disk. Such as:
The display is usually called a standard output file, and printf prints data to this file; The keyboard is commonly referred to as a standard input file, and scanf reads data from this file
We don’t discuss how the hardware devices are mapped into a file, only need to remember, in C hardware devices can be as a file, some of the input and output functions which don’t need you to indicate how to read and write files, OS has set the default file for them, also can change of course, for example let printf output data to a file on disk.
Why does the program need files?
Configuration: Text for Unix. Windows registry data: slightly large amounts of data are put in the database media: this is mandatory only binary
In reality, programs read and write files through third-party libraries, and rarely read and write binary files directly. Because such binary files are not portable, data files written on a machine with an int of 32 cannot be read directly on a machine with an int of 64, so a better solution is to use text
-
File stream: A C file is a byte stream or binary stream, all the files (stored on disk) must be loaded into memory to process, all the data must be written to the file (disk) to not lose. The process by which data is passed between files and memory is called file flow, similar to water flowing from one place to another. The process of copying data from a file to memory is called an input stream, and the process of saving data from memory to a file is called an output stream.
File is a kind of data source. Besides file, there are database, network, keyboard and so on. The data is passed into memory which is a variable stored in C
Input/output (I/O) is the operation by which a program (memory) interacts with external devices (keyboards, monitors, disks, other computers, etc.). Almost all programs have input and output operations, such as reading data from a keyboard, reading or writing data from a file on the local or network. Input and output operations can be used to receive information from the outside world, or to transmit information to the outside world. We can say that to open a file is to open a stream.
Text files with binary
-
Text file:
ASCII file is also called text file, which is a computer file. It is a typical sequential file. Each character corresponds to a byte in disk for storing the corresponding ASCII code, and the logical structure of the file is streaming file. In particular, text files refer to files stored in ASCII code (also known as text), to be more precise, English, numbers and other characters are stored in ASCII code, and Chinese characters are stored in the machine code. Text files cannot store any information except valid file characters (including carriage returns and newlines represented by ASCII characters). A text file is a computer file made up of several lines of characters. Text files exist in the computer file system. Usually, the end of a text file is indicated by placing an end-of-file flag after the last line.
-
Binary file:
Binary is according to the binary code to store, although also can be displayed on the screen, but the content can’t read, C system in dealing with these documents, not the difference between type, flow as characters, according to the byte processing, it is based on the value code files, you can specify a value according to the specific application, what’s the meaning of (such a process, Think of it as custom coding). Users generally cannot read them directly, only the corresponding software can display them. Binaries are generally executable programs, graphics, images, sounds, and so on. So it is also called a type of “streaming file”.
-
The difference between:
The difference between a text file and a binary file is not physical, but logical. The only difference is at the encoding level, text files are basically fixed-length encoding, whereas binary files are variable-length encoding, because it’s value encoding, and how many bits represent a value is up to you.
Text streams are interpreted, up to 255 characters long, in which carriage returns and newlines are converted to the newline character “\n”. (If a file is opened as “text”, all “\r\n” will be converted to “\n” when characters are read, and “\n” to “\r\n” when characters are written), binary is non-interpreted. Process one character at a time and do not convert characters.
The difference in storage: the text tool opens a file, first reads the file’s physical binary bit stream, then interprets the stream according to the decoding method chosen, and then displays the interpretation results. Generally, the decoding method chosen will be in ASCII format (a character in ASCII is 8 bits), and then it will interpret the file stream in 8 bits and 8 bits. Notepad no matter what files are opened according to the established character encoding (such as ASCII code), so when opening binary files, garbled is also a very inevitable thing, decoding and decoding do not correspond. Storing and reading text files is basically an inverse process. Access to binary files is similar to access to text files, but the encoding/decoding is different. Binary file is to output the data in memory to disk as it is stored in memory, that is, to store the original form of data. A text file outputs binary data in terminal form to a disk for storage, that is, storing the terminal form of data
Binary advantages: 1, more save a space, 2 more quickly, using binary storage to a file, 3, is the more accurate data, using binary storage will not result in a significant loss, 4, binary coding is longer, so it is flexible, had higher utilization rate of storage, decoding difficult some disadvantages: Binary, the original computer language, does not store compatibility.
Advantages of text files:
1, it is generally believed that text file encoding based on character length, decoding easier 2, text files are not necessarily ASCII to store, because ASCII code can only represent the identity of 128, open a TXT document, and then save as, there is an option is encoding, you can choose storage format, 3. Due to their simple structure, text files are widely used to record information. It avoids some of the problems encountered by other file formats
4, when parts of the text file information error, can often be easier to recover from errors, and continue to deal with the rest of the content Disadvantages: space utilization difference) binary files can use even a bit to mean a (operation), and any text file meaning at least one character at a time.
In general, the advantage of text is that it is convenient for people to read and write, and cross-platform. The disadvantage is that the input and output of the program need to be formatted, which costs a lot. The advantage of binary is that the program can read and write quickly, but the disadvantage is that it is difficult for people to read and write, and it is not cross-platform
-
Buffer:
During program execution, the additional memory provided can be used to temporarily store data in preparation for execution. It is set up to improve access efficiency, because memory access is much faster than disk drives.
When using lower-level I/O functions (contained in header files io.h and fcntl.h) to access disk directly, this approach is slow and, since it is not a standard C function, can cause problems when operating across platforms.
With standard I/O functions (contained in a header file (stdio.h), the system automatically sets buffers and reads and writes files through data streams. When a file is read, the disk is not read directly. Instead, the data stream is opened, the file information on the disk is copied to the buffer, and the program reads the required data from the buffer. When a file is written to the disk, it is not immediately written to the disk, but to the buffer first. Data is written to the disk only when the buffer is full or the file is “closed”.
Three types of buffers: full buffers:
Fill the standard I/O cache for actual I/O operations. Items on the disk are opened with standard I/O and are fully cached by default. Disk operations occur when the cache is full or when a flush operation is performed. For example, if there is a storage area in memory, say 1024 bytes in size, a program will read data from this storage area. Now the system puts the contents of a file into the storage area, and as soon as 1024 bytes are filled, the program will immediately read the 1024 bytes. As long as 1024 bytes are left unfilled, or even 1023 bytes, the program won’t read them unless it uses fflush
Buffer:
The line cache is when I/O encounters a newline character. Both standard input and standard output are row caches.
For example, if there is a storage area in memory, say 1024 bytes in size, a program will read data from this storage area. Now the system puts the contents of a file into this storage area, and if you put 10 bytes of data, you hit Enter, and the program reads it right away. If you put 20 bytes, and you hit enter, the program will read it. So even if 1024 bytes are not full, but you hit enter, the program will read it, and this is called line buffering.
No buffer:
I/O operations are not cached, and read and write streams can manipulate the actual file immediately. A classic example is standard error
For example, if there is a storage area in memory, say 1024 bytes in size, a program will read data from this storage area. Now the system puts the contents of a file into the store, and as soon as a byte is placed, the program reads it. Another byte is placed, and the program immediately reads it, so there is no buffer.
Note:
1, C language, generally must set the buffer, but when using scanf function and getCHAR, if the line buffer newline is not handled properly, the program may run exceptions or flash back phenomena. When the buffer is full, when the line buffer encounters a carriage return, and when the file is closed, use a specific function to flush the buffer
In fact, all files are ultimately binary files, text files are nothing more than the simplest way to read and write files, while binary files require special input formatting, possibly through transcoding
2. Preprocessing (header files)
Header files are files with the extension.h. They are widely used in C family programs. In general, each C program usually consists of header files and definition files. As a carrier file containing function function and data interface declaration, header file is mainly used to save the declaration of the program, while definition file is used to save the implementation of the program
Header file is the main function of multiple code files global variables (function) of the definition of reuse, prevent conflict, to the called function is given a description, its itself does not need to contain logic implementation code of the program, it only plays a role of descriptive, user program only need according to the interface declaration in the header file to invoke the correlation function or variable, The linker looks for the corresponding actual definition code from the library
Header files are the bridge and link between user applications and function libraries. The header file is not the most important part of the software, but it is an indispensable part of the C language family. At compile time, the compiler finds the corresponding function library through the header file, and then exports the actual content of the referenced function to replace the original function. Then realize the function at the hardware level
There are two types of header files: user-written headers and compiler native headers (such as
). To use a header file in a program, use the C preprocessor directive #include to reference it. Like #include
, but not necessarily in. The #include at the top of the C file is just that it inserts the entire text of that file exactly where it is, and it does that before it builds
Write all of your constants, macros, global variables, and function prototypes in a header file, and refer to them whenever you need them. This lets the compiler know that you need the data (such as the function’s prototype) to ensure that you give the correct values and types when you call
Note: Header files are usually referenced only once. Structures of the same name cannot be declared twice in the same compilation unit. If you have a structure declaration in a header file, it is very difficult for the header file not to be included more than once in the same compilation unit. If a header file is referenced twice, the compiler will process the contents of the header file twice, which will cause an error. So you need to use “standard header structure” (conditional compilation)
Standard header file structure:
Used in header files#ifdef and # ifndef are important to prevent double definition errors
#ifndef _link_ // this is a precompile instruction, check whether the _link_ macro is defined, if not, precompile the following code
Define a macro named _link_ (it doesn't matter what the name is, it's just a record)
typedef struct _link{
int number;
struct _link *nxte;
}link;
#endif // When referring to the header file again, see if the above macro does not exist, precompile the code if it does exist, skip it if it does, and prevent double include"link"Since the same class cannot be defined twice, it would be wrong to use the "standard header structure" to ensure that the header file is only used in a compilation unit# include one more time. Because when you've included this file,One called _link_ would be defined, soIf the condition of #ifndef is false, the following macro definition will not be executed. #pragma once does the same thing, but not all compilers support it
Copy the code
The #ifndef above is mainly used to avoid including header macros repeatedly. Sometimes you want to compile part of the content only if certain conditions are met. Sometimes you want to compile one set of statements when a condition is met and another set when the condition is not
Conditional references: #ifdef and #if
#ifdef identifier // Determine the identifier
#define identifier // Define identifierProgram segment 1 // executes it if defined#else Segment 2 // Executes it if it is not defined#endif It compiles segment 1 if the identifier has already been defined, and segment 2 otherwise. Among them#else Optional add or not add. In the absence of #else, section 1 is compiled if the identifier has already been defined, otherwise skip
The use of #ifdef is similar to #ifndef, but their logic is reversed. #ifdef means that if the compiler does not define an identifier and has the #else directive, all code between #else and #endif will be executedCopy the code
// Determine the value of the expression
#define identifier // Define identifier// program segment 1#else //#else is also optional// segment 2#endif It compiles segment 1 if the value of a constant expression is true (true if it is not 0), and segment 2 otherwise. Therefore can make the program under different conditions, complete different functions. It and the conditional statementif-elseSimilar to the statement, conditional compilation can also be used to make programs more portable. By changing the definition of a few keywords at the beginning of a file, you can set different values and include different files for different systemsCopy the code
Note: The “program segment” here can be a statement group or a command line.
Add: a.c file is a compilation unit, the compiler only handles one compilation unit at a time, opening more than two will cause an error
3. Links to files
In large projects, a single source file is not enough; a large amount of code needs to be separated into several files, but more importantly for modularity. We separate the code into different files for different functions or functions, so that when one function changes, we only need to recompile the relevant files, rather than compiling all the source files for the entire project.
Multiple.C files, the mian function in a compilation unit contains code that is too large to be split into several functions, and the code in a compiled code file is too long to be split into several files, but two independent source files cannot be compiled into an executable program
The header file, however, should be #inlcude wherever this function is used and defined, generally any. C files with the same name. H, place all declarations of external function prototypes and global variables (declarations only), otherwise the project will have entities with the same name in multiple compile units (some compilers allow functions with the same name in several compile units, or use the weak modifier to emphasize this existence).
In the compiler to create a new project, and then add a few source files into, for the project, some compiler will have a project in all source code files are compiled, linked, a bit of a separate compiler to compile and build two buttons, the former is to compile a single source file, the latter is for the entire project links:
// The link is in one. C fileThe #include directive contains the required header files,Use to tell the compiler that the file contains a header that is part of a preprocessed file such as a.h file named link:#ifndef _link_
#define _link_
typedef struct _link{
int number;
struct _link *nxte;
}link;
#endif A.c file:#include<stdio.h>
#include "link" // this can be referenced to the structure in the link file
int main(void){
link p;
p.number;
return 0;
}Copy the code
Links to multiple.c files:
Create a file named a.c:#include <stdio.h>
#include "t" // here we refer to the connection of the header file and access the data in the b.c fileVoid main {int I = myMax(20,40); // Here we want to call the mymax function in the b.c fileprintf("i = %d",i);
return0; } create file named b.c: int myMax(int a,int b) {// function definitionif(a>b)
return a;
else
returnb; } create a header named t.h#ifndef _link_
#define _link_int myMax(int a,int b); // Function declaration#endefCopy the code
Supplement:
1. Declaration and Definition:
The definition of a function is a definition, and the prototype of a function is a declaration. The definition of a variable is a definition, and the extrrn declaration is a declaration: int I; Extern int I is a declaration of a variable
Declarations are data that do not generate code, such as function prototypes, variable declarations, structure declarations, macro declarations, enumeration declarations, type declarations, inline functions. The definition is the data that generates the code
Closed function (static) : Adding sastic to a function makes it available only in the unit where it is compiled (the source file). Adding static to a global variable makes it available only in the unit where it is compiled
Extern: extern = extern If if you need in a program in a source file extension to another source file of the scope of the global variables, you can reference when defined function extern keyword to open to the public as a function of the variables, can let other compilation unit are accessible to the function of this unit (these two functions in the first chapter is introduction)
4, file function operation
In C language, there are no input and output statements, and the reading and writing of files are realized by library functions. ANSI specifies standard input and output functions that are used to read and write files.
(1) Open the pointer function: fopen_s (2) Read the FILE pointer fread (3) Close the FILE function
(1) Open the pointer function: fopen_s function (2) Read the FILE pointer fwrite function (3) Close the FILE function
Open file fopen function:
Note that in the fopes_s function, the two parameters represent the mode of opening the file. “read/write” corresponds to “R /w” and “b” refers to “binary method”. Rb and WB respectively indicate read/write files in binary mode.
There are no INPUT/output statements in C. All input/output functions and file operations are implemented using a set of standard library functions provided by ANSI C. Common file manipulation standard library functions are:
(Function prototype) : FILE * fopen (char *pname,char *mode). This function is declared in stdio.h. Its first argument is the name of the FILE to be opened, or rather a string address containing the filename to be changed, and its second argument is a character specifying the mode of the FILE to be opened.
1. Open the file specified by pname in the mode specified by mode. If the corresponding file specified by pname cannot be found, it will be processed in one of the following ways: (1) At this time, if mode specifies to open the file in write mode, create a new file with the name specified by pname; (2) If mode is set to open the file in read mode, an error will be generated.
(1) Assign a FILE structure variable of type FILE to the open FILE and fill it with relevant information; (2) Create a buffer; (3) Call the function of opening files or creating new files provided by the operating system to open or create specified files; FILE * : indicates that fopen is a pointer function that returns a FILE type;
3. Parameter Description pname: is a character pointer to the filename string of the file to open or create. Mode: is a character pointer to the file handling string
4. Return value Normal Return: file pointer to the opened file. NULL is returned, indicating that the operation is not successful.
Fopen () takes FILE information, including filename, FILE status, current read/write location, and so on, saves this information in a structure variable of type FILE, and returns the address of the variable.
If you want to receive the return value of fopen(), you need to define a pointer of type FILE. Such as:
FILE *fp = fopen("demo.txt"."r"); // The second parameter here can be used to change other modesCopy the code
Open the demo. TXT file in the current directory in “read only” (r) mode, and make FP point to the file, so that you can use FP to operate demo. TXT. Fp is often referred to as a file pointer.
In addition, there are different types of files. According to the storage mode of data, they can be divided into binary files and text files, and their operation details are different. This information must be provided when the fopen() function is called, and is called “file open mode.” The most basic file opening methods are as follows:
The fopen() function must be called with read/write permission, but not with read/write mode (default: “t”).
To close the file fclose function:
Once the file is used, the fclose() function should be used to close the file to free resources and avoid data loss. Fclose () : int fclose(FILE *fp); This function closes the file specified by FP, flushing the buffer if necessary. For more formal programs, the file should be checked for successful closure and returns 0 if successful, otherwise returns EOF (fclose fails if the disk is full or if the removable disk is removed or an I/O error occurs).
FILE *fp = fopen("demo.txt"."r"); // Open a file fclose(fp); // Close a fileCopy the code
1. Close the file indicated by FP. The file closure function provided by the operating system is called to close the file indicated by FP ->fd; Release the file type structure variable indicated by FP; Returns the result of the operation, which is 0 or EOF.
2. Parameter Description FP: indicates a pointer to an open file.
3. Return value Normally 0 is returned. Exception return: EOF, indicating that an error occurred while closing the file.
File input and output:
Once the file has been successfully opened, the next thing to do is to do input or output operations on the file, the simplest of which is to call the geTC (or fgeTC) and puTC (or fpuTC) functions for (single character) input and output.
Int fgetc(FILE * stream); int fgetc(FILE * stream); , fgetc() reads a character from the file referred to by the stream argument. If EOF is returned at the end of the file when no data is read, it will return that the character was read.
Getc is a macro, function prototype int getc(FILE *stream); , using the function geTC (fgeTC) to read characters from a file. The usage of geTC and fgeTC is the same. Getc call format: ch= geTC (fp); Here fp is the file pointer; The function reads a character from a file pointer and returns it as a function value to the character variable ch.
Putc is a function whose prototype is: int fputc(int ch,FILE*fp) Where ch is a character to be output. It can be a character constant or a character variable. Fp is the file pointer. The function of puTC (ch, fp) is to write the character CH to the file pointed to by the file pointer FP. If the output succeeds, the puTC function returns the output character; If the output fails, an EOF value is returned. EOF is a symbolic constant defined in the stdio.h library function file with a value equal to -1
Int fputc(int ch,FILE *fp) 1. Write ch characters to the file indicated by FP. 2. Parameter Description CH: is an integer variable, and the character to be written to the file. (In C, the integer and character can be used.) Fp: This is a file pointer that indicates the file to which characters are to be written. 3. Return value Normal Return: the code to write the character. Abnormal return: Returns EOF. For example, when trying to write a character to a “read-open” file, an error occurs and an EOF is returned. They use the same thing
// Instance: open/close file (single character)#define _GRT_SECURE_NO_WARNNGS
#include<stdio.h>
int main() { FILE *fp; // create a file structure char ch; // If the file does not exist, give a prompt and exitif ((fp = fopen("E:/C/CS1/1.txt"."rt"TXT file in CS1 under the root directory of C on disk E. Rt: read an existing file. // RT: open a text file with read-only, only read data puts()."Fail to open file!"); // If you can't open the file, print this sentenceexit(0); // And force interrupt program} // read the file until the end of the filewhile((ch = fgetc(fp)) ! = EOF) {// Fgetc putchar(ch); } putchar('\n'); fclose(fp); // Close the filereturn0; } /* FILE: struct _iobuf {char *_ptr; // Next position of file input int _cnt; Char *_base; // indicates the base position (i.e. the beginning position of the file) int _flag; // file flag int _file; // File validation int _charbuf; // Check buffer status, if there is no buffer, do not read int _bufsiz; // File size char *_tmpfname; // temporary file name}; typedef struct _iobuf FILE; * /Copy the code
-
The fgetc() and fputc() functions can read and write only one character at a time. In practice, one string or chunk of data is read and written one at a time, which is a significant increase in efficiency.
The fgets() function reads a string from the specified file and saves it into a character array (string).
Char *fgets(char * STR, int n, FILE *stream); Reads a line from the specified stream and stores it in the string pointed to by STR. It stops when (n-1) characters are read, or when a newline character is read, or when the end of the FILE is reached, depending on the case, where n is the string size and fp is a pointer to FILE.
Return value: returns the first address of the character array on success, that is, NULL on failure; If the internal pointer to the end of the file is already at the beginning of the read, no characters are read and NULL is returned, or if an error occurs, a NULL pointer is returned.
Note that the string read is automatically appended with ‘\0’ at the end, including ‘\0’ for n characters. That is, only n-1 characters are actually read, and if you want to read 100 characters, the value of n should be 101
The fputs () function has the ability to write a string to the specified file (the end of the string identifier ‘\0’ is not automatically written). After a string is successfully written, the position pointer to the file automatically moves backwards.
Int fputs(char * STR, FILE *fp); It takes two arguments: the first is the address of the string and the second is a file pointer. This function writes to a file based on the string found at the incoming address. Unlike puts, it prints the string without adding a newline to the end
Return value: STR is the string to be written, fp is the file pointer. Returns a non-negative number on success and EOF (a sign constant with a value of -1) on failure.
Example: use of fgets and fputs#include<stdio.h>
#include<stdlib.h>
#define N 10 // define the character constant N is 10int main(void) { FILE *fp; char str[N+1]; // The character array is one more than it really isif ((fp = fopen("E:/C/CS1/2.txt"."a")) == NULL) {
puts("NONONON");
exit(0);
}
/*scanf("%s", str); fputs(str, fp); // Use binary data to write filesprintfThe output will be garbled */ // the solution is to use the fprintf and fscanf functions, which will be described laterwhile(fgets(str, N, fp) ! = NULL) {printf("%s", str);
}
fclose(fp);
return0; } //fgets() encounters a newline and reads the newline into the current string. The output of this example is consistent with demo.txt, where the newline is broken, because fgets() can read the newline. Gets (), on the other hand, ignores line breaks. /* If a line break occurs before n-1 characters are read, or if the end of the file is read, the read is complete. This means that fgets() can read at most one row, no matter what the value of n is. Instead of reading a file line by line in C, we can use fgets() to set n to a large enough value to read one line at a time. * /Copy the code
-
Read and write files using formatted forms (fscanf and fprintf functions) :
The fscanf() and fprintf() functions are similar to the scanf() and printf() functions in that they are formatted reads and writes to disk files instead of keyboards and monitors. So the same rules and type specifiers that apply to scanf and printf also apply to fscanf and fprintf
Int fscanf (FILE *fp, char * format,...) ; Int fprintf (FILE *fp, char * format,...) ; // Write data to a fileCopy the code
Fp is the file pointer, format is the format control string,… Indicates a parameter list. They have only one more FP parameter than scanf() and printf(). Such as:
FILE *fp; // file pointer int I, j; char *str, ch; // Define a string and a character variable fprintf(fp,"%d %c", j, ch); // Write data to the specified file j is an integer ch is a character fscanf(fp,"%d %s", &i, str); // Reads data from the specified fileCopy the code
Return value: fprintf() returns the number of characters successfully written, or a negative number on failure. Fscanf () returns the number of successfully assigned arguments in the argument list.
When you use the fscanf and fprintf functions, you’ll find that the contents of the file are readable and clearly formatted. Using the fprintf() and fscanf() functions to read and write configuration files and log files is very convenient. It is not only recognized by programs, but also can be understood by users and can be manually modified.
If fp is set to stdin, the fscanf() function reads data from the keyboard, as scanf does; Set to stdout, the fprintf() function will output to the display, just as printf does.
Such as:
#include<stdio.h>
int main(void){
int a, b, sum;
fprintf(stdout, "Input two numbers: ");
fscanf(stdin, "%d %d", &a, &b);
sum = a + b;
fprintf(stdout, "sum=%d\n", sum);
return 0;
}Copy the code
// The usage of fprintf#include
// Write data to the file and save
#include<string.h>
#include<stdlib.h>
int main() { int a[6]; // Data is an integer int I; FILE *fp; // define a pointer to the file address fp = fopen("E:/C/CS1/2.txt"."w"); // Open the test. TXT file, w indicates write onlyif(fp == NULL) {// Exit the program if the file fails to openprintf("File cannot open! ");
exit(0);
}
printf("Please enter six integer digits separated by Spaces: \n");
for (i = 0; i < 6; i++)
{
scanf("%d", &a[i]); // Enter 6 data from the command line to save in the string}printf("The input number is: \n");
for (i = 0; i < 6; i++)
{
fprintf(fp, "%d\t", a[i]); // Format the string input data and save it to an open fileprintf("%d ", a[i]); } fclose(fp); // Close the filereturn 0;
}Copy the code
/ / the use of the fscanf#include <stdio.h>
#include <stdlib.h>
int main()
{
char str1[10], str2[10], str3[10];
int year;
FILE * fp;
fp = fopen("E:/C/CS1/2.txt"."w+"); // Open the file fputs("We are in 2015", fp); // Write data to the file rewind(fp); // Repoint the position pointer inside the file to the beginning of a stream (data stream/file) fscanf(fp,"%s %s %s %d", str1, str2, str3, &year); // Read the data from the file into the programprintf("Read String1 |%s|\n", str1); / / outputprintf("Read String2 |%s|\n", str2);
printf("Read String3 |%s|\n", str3);
printf("Read Integer |%d|\n", year); fclose(fp); // Close the filereturn(0);
}Copy the code
// Input student information to disk file, then read and output#include<stdio.h>
#include<stdlib.h>
#define N 2typedef struct _date { char name[10]; char sx[10]; int age; double socre; }date; date boya[N]; Date boyb[N]; date *pa, *pb; Int main(void) {FILE *fp; int i; pa = boya; Pb = boyb; //printf("1-%p\n", pa);
if ((fp = fopen("E:/C/CS1/1.txt"."wt+")) == NULL) //wt+ opens or creates a text file that allows reading and writing {puts()"NO NO NO!");
exit(0); } // Input from the keyboard is saved in boyaprintf("Input data: \n");
for (i = 0; i < N; i++) {
scanf("%s %s %d %lf", pa->name, pa->sx, &pa->age, &pa->socre); pa++; // Move the pointer back to store different student information. // the pa pointer points to boyb below the address of boyaprintf("2-%p\n", pa); // Write the boys data to the disk filefor (i = 0; i < N; i++) {
fprintf(fp, "%s %s %d %lf\n", pa->name, pa->sx, pa->age, pa->socre); pa++; // Reset the file pointer to rewind(fp); // Repoint the position pointer inside the file to the beginning of a stream (dataflow/file) // read data from the file to boyb in the programfor (i = 0; i < N; i++) {
fscanf(fp,"%s %s %d %lf\n", pb->name, pb->sx, &pb->age, &pb->socre); pb++; } pb = boyb; // Finally output datafor (i = 0; i < N; i++) {
printf("%s %s %d %lf\n", pb->name, pb->sx, pb->age, pb->socre); pb++; } fclose(fp); // Close the filereturn 0;
}Copy the code
-
Read and write files using data blocks (binary) (fread and Fwrite functions)
On Windows, when using fread() and fwrite(), you should open the file in binary format. The fread function reads binary data from the file and block data from the specified file. The so-called block data, which is a number of bytes of data, can be a character, can be a string, can be multiple lines of data, there is no limit.
Function prototype:
size_t fread ( void *ptr, size_t size, size_t count, FILE *fp ); size_t fwrite ( void * ptr, size_t size, size_t count, FILE *fp ); // These two functions operate on files in binary form, not just text files.Copy the code
Description of parameters:
PTR is a pointer to a memory block. It can be an array, a variable, a structure, etc. The PTR in fread() is used to hold the data read. The PTR in fwrite() is used to hold the data to be written.
2, size: indicates the number of bytes of each data block.
3. Count: indicates the number of data blocks to be read or written.
4. Fp: indicates the file pointer.
5. In theory, read and write size*count bytes at a time.
Size_t is a data type defined using typedef in the stdio.h and stdlib.h headers. It represents an unsigned integer, which is not a negative number, and is often used to represent quantities.
The return value:
Fread () : Returns the number of blocks successfully read and written, that is, count. Fwrite () : Returns a size object, which is an integer data type, if the total number of elements is successfully returned
Fread () if there is an error or the end of the file is reached, the return value may be less than count fwrite() if the size number is different from the nmemb argument, an error is displayed
-
For fwrite(), a write error must have occurred, which can be detected with the ferror() function
-
For fread(), fread doesn’t distinguish between the end of a file and an error. It may have read the end of a file, and an error may have occurred, which can be detected with ferror() or feof(). If size or count is zero, fread returns zero and does nothing else
#include<stdio.h>
#include<Stdlib.h>
#define N 2
typedef struct _date {
char name[10];
char sx[10];
int age;
double score;
}date;
date boya[N], boyb[N];
date *h, *p;
int main(void) {
FILE *fp;
int i;
h = boya;
p = boyb;
if ((fp = fopen("E:/C/CS1/x.txt"."wb+")) == NULL) {//wb+ means to open or create a binary file in read-write mode, allowing read and write. puts("NO NO NO~");
exit(0);
}
for (i = 0; i < N; i++) {
scanf("%s %s %d %lf", h->name, h->sx, &h->age, &h->score); h++; // Write the file in binary form fwrite(boya, sizeof(date),N, fp); // Write boya data to file rewind(fp); Fread (boyb, sizeof(date), N, fp); fread(boyb, sizeof(date), N, fp); // Read data from the file and save it to the structure array boyb // print datafor (i = 0; i < N; i++) {
printf("%s %s %d %f\n", p->name, p->sx, p->age, p->score); p++; } fclose(fp);return 0;
}Copy the code
-
Random read and write files will be introduced: rewind function and fseek function and ftell function
The previous file read and write functions are sequential, that is, files can only be read and written from the beginning, and each data can be read and written in sequence. However, in real development, it is often necessary to read and write the middle part of the file. To solve this problem, we must first move the position pointer inside the file and then read and write. This type of reading and writing is called random reading and writing, which means reading and writing from anywhere in the file. The key to implementing random reads and writes is to move the position pointer as required. This is called file positioning.
There are two main functions to move the position pointer inside a file, rewind() and fseek() :
Void rewind(FILE *stream); Int fseek(FILE *stream, long offset, int fromWHERE); Long ftell(FILE *stream); long ftell(FILE *stream); // Returns the current file locationCopy the code
Stream in rewind and ftell is a file pointer.
In fseek, stream is the file pointer, and offset represents the offset, which is the number of bytes to move. The reason for the long type is that you want to move more and process more files. If offset is positive, it moves backward. If offset is negative, move forward. Fromwhere is the starting position, where the offset is calculated from. Each position is represented by a constant: (The beginning of the file: SEEK_SET constant value is 0) (the current position of the file: SEEK_CUR constant value is 1) (the end of the file: SEEK_END constant value is 2)
Note: 1. Fseek () is usually used in binary files. After moving the position pointer, you can read and write using any of the read and write functions described earlier. Since they are binary files, fread() and fwrite() are commonly read and written.
File Pointers point to files/streams. The position pointer points to a byte position inside a file and moves as the file is read. The file pointer will not change or point to another file without reassigning.
2. Rewind () is not a file pointer but a position pointer inside the file that moves backwards as the file’s position pointer (pointing to the current read/write byte) is read or written to the file. The file pointer points to the entire file and does not change if you do not reassign.
3. It is very easy to determine the current location of the file by calling ftell() after using the fseek function.
Return value: ftell(); Return a value of long representing the size of the current file location
rewind(); No return value
fseek (); Returns 0 on success, non-0 on failure, and sets the value of error, which can be printed using perror()
Supplement: ftell (fp); The ftell() function makes it easy to know the length of a file. Such as the following statement sequence: fseek(fp, 0L,SEEK_END); len =ftell(fp); First move the current position of the file to the end of the file, and then call the function ftell() to get the displacement of the current position relative to the beginning of the file, which is equal to the number of bytes contained in the file.
#include<stdio.h>
#include<stdlib.h>
#define N 3 // Three students
typedef struct _date {
char name[10];
char sex[10];
int age;
double score;
}date;
date boys[N];
date *pb;
date boy;
int main(void) {
FILE *fp;
int i;
pb = boys;
if ((fp = fopen("E:/C/CS1/t.txt"."wb+")) == NULL) {
printf("NONONON");
exit(0);
}
for (i = 1; i <=N; i++) {
scanf("%s %s %d %lf", pb->name, pb->sex, &pb->age, &pb->score); pb++; } fwrite(boys, sizeof(date), N, fp); fseek(fp, 0l, SEEK_SET); Fread (&boy, sizeof(date), N, fp);printf("%s %s %d %lf\n", boy.name, boy.sex, boy.age, boy.score); // fseek(fp, 10l, SEEK_SET); // fseek(fp, -10l, SEEK_END); Return 10 bytes fseek(fp, sizeof(date), SEEK_SET) from the end of the file; // Move pointer fread(&boy, sizeof(date), N, fp) from start position;printf("%s %s %d %lf\n", boy.name, boy.sex, boy.age, boy.score); // Output the second student information fclose(fp);return 0;
}Copy the code
-
Other library functions:
Getw reads an integer in binary form putW stores an integer in binary form
File status check function: feof File end ferror file read/write errors clearErr Clear file error flags ftell Learn about the current position of the file pointer fgetpos Obtains the current position of the access pointer. Fsetpos locates the file pointer on the stream
Fdopen turns file descriptors into file Pointers fflush updates buffers setbuf sets the buffers of file streams setvbuf sets the buffers of file streams Fileno returns the file descriptors used by file streams mktemp generates a unique temporary file name ungeTC writes specified characters back into the file stream