File operation
ππ Take your own notes ~: Document operation notesππ
β€οΈ Welcome friends who like learning C/C + + to work together!! β€οΈ
introduction
I published an article about the address book a few days ago. After entering my contact information, if I quit the program, my contact information will disappear. The address book we want may not be like this. What we want is that the address book can keep our contact information all the time
Address book article directions: Simple address book implementation, gitee also updated the dynamic memory version of the address book
This article will introduce how to save our contact information through file operation
1, Common file types
The classification of documents is shown in the figure below
1. Procedure documents
-
π Source program file (suffix. c)
-
π Target file (windows environment suffix is. obj)
-
π Executable program (windows environment suffix is. exe)
2. Data files
β¨ Sometimes we need to read the data and output the content when running the program
3. File name
β¨ I believe everyone is familiar with how the file name is formed
File path + file name trunk + file suffix
- For example: c:\code\test.txt
2, File pointer
β οΈ β οΉ₯ operation steps:
- β Open file
- β Read / write data
- β Close file
π Every time we open a file, a pointer will point to a file information area, which is used to store the relevant information of the file (such as file name, file status, current location of the file, etc.)
π This information is stored in a structure variable. The structure type is declared by the system and is called FILE
In fact, in vs2019, corecrt_ This is described in the wstdio. H header file
vs2019 may be deeply encapsulated, which is not easy to observe
Let's take a look at vs2013, which is described in the stdio.h header file
struct _iobuf { char *_ptr; int _cnt; char *_base; int _flag; int _file; int _charbuf; int _bufsiz; char *_tmpfname; }; typedef struct _iobuf FILE;
In this way, we can see clearly what data is stored in it
β¨ 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 the FILE structure are maintained through a FILE pointer, which is more convenient to use
β¨ Definition f is a pointer variable pointing to data of type FILE. You can make pf point to the FILE information area (a structure variable) of a FILE. The FILE pointer variable can find the FILE associated with it through the FILE information area.
3, Opening and closing of files
1. Open fopen file
//Open file FILE * fopen (const char * filename, const char * mode);
β οΈ β If the opening fails, a null pointer is returned β οΈ β οΈ
- filename is the file name
- Mode is the open mode
β¨β¨ What are the types of mode opening methods
File usage | meaning | If the specified file does not exist |
---|---|---|
"r" (read only) | To enter data, open an existing text file | error |
"w" (write only) | To output data, open a text file | Create a new file |
"a" (added) | Add data to the end of a text file | Create a new file |
"rb" (read only) | To enter data, open a binary file | error |
"wb" (write only) | To output data, open a binary file | Create a new file |
"ab" (additional) | Add data to the end of a binary file | error |
"r +" (read / write) | To read and write, open a text file | error |
"w +" (read / write) | A new file is recommended for reading and writing | Create a new file |
"a +" (read / write) | Open a file and read and write at the end of the file | Create a new file |
"rb +" (read / write) | Open a binary file for reading and writing | error |
"wb +" (read / write) | Create a new binary file for reading and writing | Create a new file |
"ab +" (read / write) | Open a binary file and read and write at the end of the file | Create a new file |
This paper mainly introduces and understands the first three ways
2. "r" reads the file
Let's try reading the file first
I'll create a new txt file on the desktop first
Write according to the code of the open file, and pay attention to prevent null pointers
#include <stdio.h> #include <stdlib.h> int main() { FILE * f = fopen("file.txt", "r"); if (f == NULL) { perror("fopen");//Judge whether the opening is successful return -1; } return 0; }
β οΈ β The result is that it tells me that there is no such file!
β οΈ β οΈ β Note: this method of writing only the name is called passing the relative path address. If only the file name is written, the file must be in the same path of the source file to be read successfully
π We need to write all its paths, which is called passing absolute path address
Right click the file, find the properties, and find its path
π Modify the code: note that the combination of \ and letters will cause escape characters, so you need to add \ in front to avoid escape
int main() { FILE * f = fopen("C:\\Users\\yujing wang\\Desktop\\file.txt", "r"); if (f == NULL) { perror("fopen"); return -1; } return 0; }
π’π’π’ After running, I still failed to read??
It took me a long time to find out why
π₯π₯π₯ It turns out that when my computer creates a new file, it doesn't need to define what type of file it is. It will be added automatically, and the file.txt I wrote is the file name and TXT is the file type, so I'll check whether the name is correct when looking for its path
This time we will not modify the code, but directly modify the file name
π₯ This read succeeded!
Let's enter the characters file in the file and try how to print the read characters
fgetc read character function
Parameters and return values
int fgetc( FILE *stream );
int main() { FILE * f = fopen("C:\\Users\\yujing wang\\Desktop\\file.txt", "r"); if (f == NULL) { perror("fopen"); return -1; } int ret = fgetc(f); printf("%c", ret); ret = fgetc(f); printf("%c", ret); return 0; }
The operation results are as we wish
3. fclose close file
//Close file int fclose ( FILE * stream );//The address of the file information area is transmitted
Directly use the above code to open the file and add the close file later
β¨β¨β¨ Note that the pointer does not change after use. You need to change it into a null pointer β¨β¨β¨
int main() { FILE * f = fopen("C:\\Users\\yujing wang\\Desktop\\file.txt", "r"); if (f == NULL) { perror("fopen"); return -1; } fclose(f); f = NULL; return 0; }
4. "w" write file
π We delete the file created on the desktop just now, and then execute the original code, but the opening method is "w"
int main() { FILE * f = fopen("C:\\Users\\yujing wang\\Desktop\\file.txt", "w"); if (f == NULL) { perror("fopen"); return -1; } fclose(f); f = NULL; return 0; }
The result is
β¨ There are many newly added files on the desktop. If you write something in the file and run the code, the file will become an empty file again. It's amazing
We can also add characters to the file in the code
fputc character input function
Parameters and return values
int fputc( int c, FILE *stream );
Pass in the file address and write characters to the file
int main() { FILE * f = fopen("C:\\Users\\yujing wang\\Desktop\\file.txt", "w"); if (f == NULL) { perror("fopen"); return -1; } fputc('f', f);//Character input function fputc('i', f); fputc('l', f); fputc('e', f); fclose(f); f = NULL; return 0; }
After running, we open the file
We write a file to the file in code
4, Sequential reading and writing of files
Sequential read-write function table
function | Function name | Apply to |
---|---|---|
Character input function | fgetc | All input streams |
Character output function | fputc | All output streams |
Text line input function (read contains' \ 0 ') | fgets | All input streams |
Text line output function | fputs | All output streams |
Format input function (read in one format) | fscanf | All input streams |
Format output function | fprintf | All output streams |
Binary input | fread | file |
Binary output (write as binary) | fwrite | file |
β¨ External devices: file, screen, network, CD, floppy disk
β¨ A stream is a device that can be read and written to
c language programs open three streams by default when running
Standard output stream - stdout (screen printing, where the screen is the compiler debugging console)
π« Standard input stream - stdin (keyboard)
π« Standard error stream - stderr
π« These stream types are FILE*
The character input function fgetc and character output function fputc have been introduced earlier
1. fputs text line output function
Parameters and return values
int fputs( const char *string, FILE *stream );
Pass parameter, write the text line and the address of the file
0 is returned for success and NULL is returned for failure
First of all, there is no such file on the desktop. We need to write a file with a string content of file
#include <stdio.h> #include <stdlib.h> int main() { FILE* p = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "w"); if (p == NULL) { perror("fopen"); return -1; } fputs("file", p); fclose(p); p = NULL; return 0; }
The operation structure is that there are more files on the desktop, test.txt, with the content of file, which is much simpler than the previous one character input
After the code runs, let's read the string
2. fgets text line output function
Parameters and return values
char *fgets( char *string, int n, FILE *stream );
Parameter transfer: the location where the string is stored, the number of bytes transferred (no more than the maximum number of bytes), and the file address
ps: the bytes passed here contain '\ 0' by default
The starting address of string is returned successfully, and NULL is returned in case of failure
Go directly to the code:
#include <stdio.h> #include <stdlib.h> int main() { FILE* p = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "r"); if (p == NULL) { perror("fopen"); return -1; } char arr[5] = { 0 }; char* ret = fgets(arr, 5, p); printf("%s\n", arr); printf("%s\n", ret); fclose(p); p = NULL; return 0; }
Operation results:
Both printing methods are available
3. fprintf format output function
Parameters and return values
int fprintf( FILE *stream, const char *format [, argument ]...);
Transmission parameters: file address, formatted memory (this format has a certain format for the content)
Functions in "" similar to printf
Return value: several bytes are successfully written
The code is similar to the previous ones
struct stu { int a; char b[4]; }st = {233, "abc"}; int main() { FILE* p = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "w"); if (p == NULL) { perror("fopen"); return -1; } int ret = fprintf(p, "%d %s", st.a, st.b); printf("%d", ret); fclose(p); p = NULL; return 0; }
effect:
4. fscanf format input function
Parameters and return values
int fscanf( FILE *stream, const char *format [, argument ]... );
Transmission parameters: file address, formatted memory (this format has a certain format for the content)
According to the code that has been output above, let's input it into the structure
#include <stdio.h> #include <stdlib.h> struct stu { int a; char b[4]; }st; int main() { FILE* p = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "r"); if (p == NULL) { perror("fopen"); return -1; } fscanf(p, "%d %s", &(st.a), st.b); printf("%d %s\n", st.a, st.b); fclose(p); p = NULL; return 0; }
Operation results:
5. fwrite binary output function
Parameters and return values
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );
Parameters: pointer to the data to be written, byte size of an element, maximum number of elements, and file address
Return value: the number of elements actually written by the book
Experiment:
struct stu { int a; char b[4]; }st = {233, "abc"}; int main() { FILE* p = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "wb"); if (p == NULL) { perror("fopen"); return -1; } int ret = fwrite(&st, sizeof(st), 1, p); printf("%d", ret); fclose(p); p = NULL; return 0; }
Operation results:
Here, letters written in binary form are letters, while binary written numbers we can't see
6. fread binary input function
Parameters and return values
size_t fread( void *buffer, size_t size, size_t count, FILE *stream );
Parameters: the pointer points to the position where the read data is placed, the byte size of an element, the maximum number of elements, and the file address
Also read according to the above code
struct stu { int a; char b[4]; }st; int main() { FILE* p = fopen("C:\\Users\\yujing wang\\Desktop\\test.txt", "rb"); if (p == NULL) { perror("fopen"); return -1; } fread(&st, sizeof(st), 1, p); printf("%d %s", st.a, st.b); fclose(p); p = NULL; return 0; }
It seems that the reading succeeded
Summary
I've been wondering for a long time, π What is the difference between fprintf and printf? Is there any connection
scanf/fscanf/sscanf
printf/fprintf/sprintf
What are these two groups of very similar functions
function | effect |
---|---|
scanf | Read formatted data from standard input stream (keyboard) |
fscanf | Read formatted data from all input streams |
sscanf | Read a formatted data from a string (convert a string into a formatted data) |
printf | Output formatted data to standard output (screen) |
fprintf | Output formatted data to all output streams (screens / files) |
sprintf | Convert the formatted data into the corresponding string! |
Although we don't use programs to write a txt file, we need to know the operation principle,
π When necessary, it will also bring convenience!
I have Baidu search
In fact, its examples are hidden in our lives πππ~~