In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to operate C language files, I believe many inexperienced people are at a loss about this. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
I. Preface
How can we make the program we design have "memory function"? The answer is to save the data separately as a file. There are many forms of preservation, in this article we keep in the simplest form of text in notepad, I believe that this article will let you learn.
II. Basic knowledge of file operation ① what is a file
We usually talk about two kinds of documents: program files and data files.
Includes source program files (suffix .c), destination files (windows environment suffix .obj), and executable programs (windows environment suffix .exe).
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 the data, or the file from which the content is output.
This chapter discusses data files
② data file type
Text files and binary files
The data is stored in memory in binary form, which is (suffix .bin) if it is output to external memory without conversion.
If it is required to be stored in the form of an ASCII code on external memory, it needs to be converted before storage. Files stored in ASCII characters are (suffix .txt).
How ③ data is stored
How is a data stored in memory?
All characters are stored in ASCII form, and numeric data can be stored either in ASCII form or in binary form.
If there is an integer 10000, if it is output to disk in the form of ASCII code, it takes up 5 bytes on the disk (stored in one character per character, 10000 one byte per character), while output in binary form takes only 4 bytes on the disk (int).
How to read binary files by ④
Text files can be understood and read directly through notepad, while binary files that are opened in notepad form are garbled that we cannot recognize. However, vs can read binaries in some way as follows:
(the following figure shows 10000 saved in binary form in notepad)
Demonstrate how binaries are opened:
Step 1: add the file to the vs
Step 2: right-click and open the mode and select the binary compiler
This is the final effect.
⑤, what is a file name?
The file name contains three parts: file path + file name backbone + file suffix
For example: C:\ code\ test.txt (absolute and relative references to file names will be mentioned later)
⑥ file buffer
Meaning: the ANSIC standard uses data files processed by the "buffer file system". The so-called buffered file system means that the system automatically opens a "file buffer" in memory for every file being used in the program. A file buffer is a certain amount of space reserved in the memory area for temporarily storing file data during reading and writing. Realized by disk cache, disk cache itself is not an actual storage medium, it relies on fixed disk and provides the expansion of main storage space, that is, using the storage space in main memory, to temporarily store information read (or written) from the disk.
Features: the output data from memory to disk will first be sent to the buffer in memory, and then sent to the disk together after the buffer is full. If you read data from the disk to the computer, read the data from the disk file into the memory buffer (full of buffers), and then send the data one by one from the buffer to the program data area (program variables, etc.). The size of the buffer is determined by the C compilation system.
[extension-three types of cache] links-file buffers
⑦ file pointer
In the buffered file system, the key concept is "file type pointer", or "file pointer" for short. Each used file has a corresponding file information area in memory, which is used to store information about the file (such as the name of the file, the status of the file, and
The current location of the file, etc. This information is stored in a structural variable. The structure type is systematically declared and is named FILE.
Whenever you open a file, the system will automatically create a variable of the FILE structure according to the situation of the file, and fill in the information in it, so that the user does not have to pay attention to the details. Generally, a pointer to FILE is used to maintain the variable of the FILE structure, which is more convenient to use.
FILE*p// file type pointer
You can make pf point to the file information area (which is a structural variable) of a file. The file can be accessed through the information in the information area of the file. That is, the file associated with it can be found through the file pointer variable.
Third, file operation functions ① fopen and fclose
1.fopen
Open a file
Filename- file name mode- opening method
A file pointer
(open mode table)
2.fclose
Close the file
Stream- file pointer
3. Use demonstration
# include#include#includeint main () {FILE*pw = fopen ("test.txt", "w"); / / the open file is "test.txt" with "w" if (pw==NULL) / / if the opening fails, it indicates the reason for the failure and ends the process {printf ("% s", strerror (errno)); / / errno is the global error variable strerror parses errno to the error cause return 0 } fclose (pw); / / close the file pw = NULL;// and set the pointer to null to prevent misuse of return 0;}
File name relative / absolute path
Absolute path: for example, c:\ code\ test.txt contains file path file backbone file suffix
Relative path: the representation of the above figure is the relative path, indicating that the txt file and the source file are in the same path. If you want to express the strength all the way up, use ".. /". The path on one analogy is ".. /.. /".
FILE*pw = fopen (".. / test.txt", "w")
② fputc and fgetc
1. Fputcmusic-output function
Write a character to the stream
C-output character
Normal-returns the output character
Error-return EOF
All streams
2. Fgetcmusic-input function
Read a character from the stream
Int-- returns the characters entered
An error occurred in EOF-- or reached the end of the file
All streams
3. Use demonstration
# include # include # include//fputc outputs one letter: int main () {FILE*pw = fopen ("test.txt", "w"); if (pw = = NULL) {printf ("% s", strerror (errno)); return 0;} fputc ('baked dome pw) / / write the character'b' to the file "test.txt" fclose (pw); pw = NULL; return 0;} / / fgetc reads one character, and the file pointer after reading is offset by one bit int main () {FILE*pr = fopen ("test.txt", "r"); if (pr = = NULL) {printf ("% s", strerror (errno)) Return 0;} char ch = 0 pr / receive the input character ch = fgetc (pr) with ch; / / read from the file "test.txt". After reading a character, the file pointer automatically moves back one bit fclose (pr); pr = NULL; printf ("% c", ch); return 0;}
4. Understanding of all streams
What is a stream: a stream is the process by which information is input from an external input device (such as a keyboard) to the inside of a computer (such as memory) and output from memory to an external output device (monitor).
The above code demonstrates the operation of the file stream, and we are demonstrating it with the standard input (stdin) output (stdout) stream
③ fputs and fgets
1. FputsWhile-output function
Write a string to the stream
Non-negative value of int-- indicates success
An error occurred in EOF--
All streams
2. FgetsWhile-input function
Get a string from a stream
Normal-returns a string
NULL-- indicates an error or reached the end of the file
N-the maximum number of characters read from the stream (\ 0 will automatically take one bit)
3. Use demonstration
# include # include # include//fputsint main () {FILE*pw = fopen ("test.txt", "w"); if (pw = = NULL) {printf ("% s", strerror (errno)); return 0;} char ch [5] = "abcd"; fputs (ch,pw); fclose (pw); pw = NULL Return 0;} / / fgetsint main () {FILE*pr = fopen ("test.txt", "r"); if (pr = = NULL) {printf ("% s", strerror (errno)); return 0;} char ch [5] = {0}; fgets (ch,3,pr) / / A bit is automatically occupied by\ 0 printf ("% s", ch); return 0;} ④ fprintf and fscanf
1.fprintfmurf-output function
Write data in a specific format to the stream
Returns the number of bytes printed.
All streams
Printf prints the data on the standard output stream (stdout) by default, while the output stream of fprintf can be selected. The number of characters printed by printf returns
2. Fscanfmusic-input function
Read data in a specific format from a stream
All streams
Returns the number of fields successfully converted and assigned
3. Use demonstration
/ / the header file is the same as above / / fprintfint main () {FILE*pw = fopen ("test.txt", "w"); if (pw = = NULL) {printf ("% s", strerror (errno)); return 0;} fprintf (pw, "% d% .2f% c", 10Magne3.14); fclose (pw); pw = NULL Return 0;} / / fscanfint main () {int a; float b; char c; FILE*pr = fopen ("test.txt", "r"); if (pr = = NULL) {printf ("% s", strerror (errno)); return 0;} fscanf (pr, "% d% f% c", & a) Printf ("d% .2f% c", a return bjorc); return 0;} ⑤ fwrite and fread
1.fwriteWhile-output function
Write data to the file stream in binary form
Buffer- points to the pointer to write data the size of each element size- the maximum number of elements written by count-
Number of elements actually written
File stream
2. Freadhouse-input function
Read data from a file stream in binary form
Number of elements actually read in
File stream
3. Use demonstration
/ / header file as above / / fwrite freadtypedef struct stu {int n; float score; char name [10];} stu; int main () {stu s = {10100.0, "Zhang San"}; FILE*pr = fopen ("test.txt", "rb"); struct stu S1 = {0} If (pr = = NULL) {printf ("% s", strerror (errno)); return 0;} / / fwrite (& s meme sizeof (stu), 1pw); fread (& s 1m m sizeof (stu), 1m p r); fclose (pr); pr = NULL; return 0;} ⑥ fseek and ftell and rewind
1.fseek
Moves the file pointer to the specified location
Offset- offset origin- initialization file pointer location
There are three options for origin: SEEK_CUR starts from the current location
SEEK_END starts at the end of the file
SEEK_SET starts at the beginning of the file
Success returns 0, failure returns non-0
The modification of the file pointer can not be done by pairing + first.
Use the demo (it is now known that notepad saves data as "abcdef")
/ / fseekint main () {FILE*pr = fopen ("test.txt", "r"); int a = 0; if (pr = = NULL) {printf ("% s", strerror (errno)); return 0;} / locate the file pointer fseek (pr,-1, SEEK_END) / / points to the last a=fgetc (pr); b=ftell (pr); / / returns the current pointer position printf ("% c", a); printf ("% d", b); fclose (pr); pr = NULL; return 0;}
(if the initialization file pointer is SEEK_SET, offset 1 will get b)
2.ftell
Returns the offset of the current file pointer
3.rewind
Return the file pointer to the beginning of the file
Use demo
Int main () {int n; FILE * pFile; char buffer [27]; pFile = fopen ("test.txt", "w +"); for (n ='lf; n = 1) {printf ("% lf\ n", b) } if (feof (fp)) printf ("Error reading test.bin: unexpected end of file\ n"); else if (ferror (fp)) {perror ("Error reading test.bin");} fclose (fp); fp = NULL;} ⑧ supplementary function sscanf sprintf
1.sprintf
Write data in a specific format to a string
Storage location of buffer- output
Data size written to the string (in bytes)
2.sscanf
Read a string in a specific format from a string
3. Use demo
/ / sprintf sscanftypedef struct stu {int n; float score; char name [10];} stu; int main () {stu s = {10Last 3.14, "Zhang San"}; char buf1 [1024] = {0}; stu S1 = {0}; sprintf (buf1, "% d% f% s", s.npene s.scorerewrits.name); / / Don't add nasty. Sscanf (buf1, "% d% f% s", & (s1.n), & (s1.score), & (s1.name)); printf ("% d\ n", s1.n); printf ("% s\ n", s1.name); return 0;} ⑨ supplementary function perror strerror
Compared with strerror, perror does not need to reference errno variables and does not need to use printf functions, so it is more convenient to operate. At the same time, the self-input string plays the role of identification and will not be confused.
Summary
This is the end of this article on C language file operation zero basic beginner nanny-level tutorials, more related C language file operation zero basic tutorials, please search the previous articles or continue to browse the following related articles hope that you will support more in the future!
After reading the above, have you mastered the method of how to operate C language files? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.