当前位置:网站首页>Detailed explanation of document operation
Detailed explanation of document operation
2022-07-24 14:51:00 【Qingfeng jade bone ( ω・)「 well】
Catalog
Random, speaking, reading and writing
Determination of the end of file reading
Role of documents
Using files, we can store data directly on the hard disk of the computer , Data persistence is achieved
What is a document
The files on disk are files .But in programming , There are two kinds of documents we usually talk about : Program files 、 Data files ( Classified from the perspective of file function )
Program files :
Include source files ( The suffix is .c), Target file (windows Environment suffix is .obj), Executable program (windows Environment suffix is .exe)Data files :The content of the file is not necessarily a program , It's the data that the program reads and writes when it runs , For example, the file from which the program needs to read data , Or outputfile name :A file should have a unique file ID , So that users can identify and reference .The filename contains 3 part : File path + File name trunk + file extensionfor example : c:\code\test.txt

The file pointer
Buffer file system , The key concept is “ File type pointer ”, abbreviation “ The file pointer ”.Each used file has a corresponding file information area in memory , It is used to store information about files ( Such as the name of the document , File status and current file location, etc ). This information is stored in a structure variable . The structure type is system declared , The name FILE.
such as :struct _iobuf {char *_ptr;int _cnt;char *_base;int _flag;int _file;int _charbuf;int _bufsiz;char *_tmpfname;};typedef struct _iobuf FILE;
Now we can create a FILE* Pointer variable for :
FILE* pf;// File pointer variable
Definition pf It's a point FILE Pointer variable of type data . You can make pf Point to the file information area of a file ( It's a structural variable ). Through the information in the file information area, you can access the file . in other words , Through the file pointer variable, you can find the file associated with it .
Opening and closing of files
fopen And fclose
Prototype
fopen
<stdio.h>
FILE * fopen ( const char * filename, const char * mode );
fclose
<stdio.h>
int fclose ( FILE * stream );
If you open it, you close it
Open mode
How files are used meaning If the specified file does not exist"r"( read-only ) To enter data , Open an existing text file error"w"( Just write ) To output data , Open a text file Create a new file"a"( Additional ) Add data to the end of the text file Create a new file"rb"( read-only ) To enter data , Open a binary file error"wb"( Just write ) To output data , Open a binary file Create a new file"ab"( Additional ) Add data to the end of a binary file error"r+"( Reading and writing ) For reading and writing , Open a text file error"w+"( Reading and writing ) For reading and writing , Suggest a new file Create a new file"a+"( Reading and writing ) Open a file , Read and write at the end of the file Create a new file"rb+"( Reading and writing ) Open a binary file for reading and writing error"wb+"( Reading and writing ) For reading and writing , Create a new binary file Create a new file"ab+"( Reading and writing ) Open a binary file , Read and write at the end of the file Create a new file
Example
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
FILE* pf = fopen("test.txt", "r");// Here it is opened by reading , Because there is no such file under the file, it failed
if (pf == NULL) // If it fails to open, it will return NULL
{
printf("%s\n",strerror(errno)); // Display error
return 1;
}
// Reading documents
//……
// Close file
fclose(pf); // Close the file after use
pf = NULL; // Set it to null pointer , Prevent random rotation
return 0;
} 
Example ( repair )


Read and write functions
function Function name Apply toCharacter input function fgetc All input streamsCharacter output function fputc All output streamsText line input function fgets All input streamsText line output function fputs All output streamsFormat input function fscanf All input streamsFormat output function fprintf All output streamsBinary input fread fileBinary output fwrite file
fputc
int fputc ( int character, FILE * stream ); // here int Because of the character ASCLL Code value
Writing documents
Example
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
FILE* pf = fopen("test.txt", "w");
if (pf == NULL) // If it fails to open, it will return NULL
{
printf("%s\n", strerror(errno));
return 1;
}
// Writing documents
char i = 0;
for ( i = 'a'; i < 'z'; i++)
{
fputc(i ,pf);
}
// Close file // Files are also resources , The number of openings is limited , So remember to close the file
fclose(pf);
pf = NULL;
return 0;
}
Reading documents
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
FILE* pf = fopen("test.txt", "r"); // Open as read Data has been written before
if (pf == NULL) // If it fails to open, it will return NULL
{
printf("%s\n", strerror(errno));
return 1;
}
Writing documents
//char i = 0;
//for ( i = 'a'; i < 'z'; i++)
//{
// fputc(i ,pf);
//}
Reading documents
int ch = fgetc(pf); // Read once and move backwards
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
// Close file // Files are also resources , The number of openings is limited , So remember to close the file
fclose(pf);
pf = NULL;
return 0;
}
When reading fails ( Read to the end )
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL) // If it fails to open, it will return NULL
{
printf("%s\n", strerror(errno));
return 1;
}
int ch = 0;
while ( (ch = fgetc(pf) ) != EOF )
{
printf("%c ", ch);
}
printf("\n");
// Close file // Files are also resources , The number of openings is limited , So remember to close the file
fclose(pf);
pf = NULL;
return 0;
} 
fputs
Prototype
int fputs ( const char * str, FILE * stream );
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
FILE* pf = fopen("test.txt", "w"); // write in // The addition should be changed to 'a'
if (pf == NULL) // If it fails to open, it will return NULL
{
printf("%s\n", strerror(errno));
return 1;
}
Write a line of data to the file
fputs("hello world!", pf);
// Close file // Files are also resources , The number of openings is limited , So remember to close the file
fclose(pf);
pf = NULL;
return 0;
} 
Be careful : The clear data here refers to the data in the program that has not been run

fgets
Prototype
char * fgets ( char * str, int num, FILE * stream )
Return value

Read successful : Return the address where the data is stored
Read failed : When you read the end of the article or encounter an error when reading NULL
Example
//fgets // Read a row of data
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
FILE* pf = fopen("test.txt", "r"); // write in
if (pf == NULL) // If it fails to open, it will return NULL
{
printf("%s\n", strerror(errno));
return 1;
}
Read a line of data to the file
char arr[20] = { 0 };
fgets(arr, 5, pf);
printf("%s\n", arr);
// Close file // Files are also resources , The number of openings is limited , So remember to close the file
fclose(pf);
pf = NULL;
return 0;
}
Memory data change

perror
amount to printf("%s\n", strerror(errno));

fprintf
write in
Prototype
int fprintf ( FILE * stream, const char * format, ... );
Example
#include<stdio.h>
struct S
{
char arr[10];
int age;
float score;
};
int main()
{
struct S s = { "zhangsan",25,50.5f };
FILE* pf = fopen("test.txt", "w");
if (pf == NULL)
{
perror("fopen");
return 1;
}
//
fprintf(pf, "%s %d %f", s.arr, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}

fscanf
Reading data
Prototype
int fscanf ( FILE * stream, const char * format, ... );
Example
#include<stdio.h>
struct S
{
char arr[10];
int age;
float score;
};
int main()
{
struct S s = { 0 };
FILE* pf = fopen("test.txt", "r"); // Here is the data reading , Read from file
if (pf == NULL) // The data has been written before
{
perror("fopen");
return 1;
}
fscanf(pf, "%s %d %f", s.arr, &s.age, &s.score);
printf("%s %d %f\n", s.arr, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}
Simply understand the flow
flow
//FILE*
//printf
//scanf
Any one of them C Program , As long as it runs, it will clock in by default 3 A flow
FILE* stdin - Standard input stream ( keyboard )
FILE* stdout - Standard output stream ( The screen )
FILE* stderr - Standard error flow ( The screen )

Here, the data can also be directly printed out by using the standard output stream
fwrite
Output in binary -- Write
Prototype
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
Four parameters
1. Address , Address of the data to be written
2. size , The size of such data
3. Number , How many such data are written
4. The pointer , The file pointer
#include<stdio.h>
struct S
{
char arr[10];
int age;
float score;
};
int main()
{
struct S s = { "zhangsan",25,50.5f };
FILE* pf = fopen("test.txt", "wb");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Write... In binary
fwrite(&s, sizeof(struct S), 1, pf);
fclose(pf);
pf = NULL;
return 0;
}

there zhangsan It can be seen that the binary mode is the same as the text mode , So we can understand
We can do it in VS Put this inside txt Add to it , Right click open mode to open in binary mode , You can see the appearance of its binary file . Of course, writing in binary mode naturally requires reading in binary mode , The following demonstration
fread
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
Return value : Return the actual number of reads
#include<stdio.h>
struct S
{
char arr[10];
int age;
float score;
};
int main()
{
struct S s = { 0 };
FILE* pf = fopen("test.txt", "rb");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Read in binary
fread(&s, sizeof(struct S), 1, pf);
printf("%s %d %f\n", s.arr, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}

So we can understand
sscanf And sprintf
These two are not functions of file operation
Prototype
sprintf
int sprintf ( char * str, const char * format, ... );
sscanf
int sscanf ( const char * s, const char * format, ...);

Example
#include<stdio.h>
struct S
{
char arr[10];
int age;
float score;
};
int main()
{
struct S s = { "zhangsan",25,50.5f };
char buf[100] = {0};
struct S tmp = { 0 };
//sprintf
// hold s The formatted data in is converted into a string and placed in buf in
sprintf(buf, "%s %d %f", s.arr, s.age, s.score);
printf(" character string :%s\n", buf);
//sscanf
// From a string buf Get a formatted data to tmp in
sscanf(buf, "%s %d %f", tmp.arr, &tmp.age, &tmp.score);
printf(" format :%s %d %f\n",tmp.arr,tmp.age,tmp.score);
return 0;
}
Random, speaking, reading and writing
Locate the file pointer according to its position and offset
fseek
Prototype
int fseek ( FILE * stream, long int offset, int origin );

Three positioning symbols
SEEK_SET -- Read from file
SEEK_CUR -- Offset backward from the read position
SEEK_END -- Read from the end of the file
#include<stdio.h>
#include<errno.h>
#include<string.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Reading documents
// Locate file pointer
//SEEK_SET
fseek(pf, 2, SEEK_SET);
int ch = fgetc(pf);
printf("%c\n", ch);
//SEEK_CUR
fseek(pf, 2, SEEK_CUR);
ch = fgetc(pf);
printf("%c\n", ch);
//SEEK_END
fseek(pf, -1, SEEK_END);
ch = fgetc(pf);
printf("%c\n", ch);
return 0;
}


ftell
Calculate the current offset
Prototype
long int ftell ( FILE * stream );
#include<stdio.h>
#include<errno.h>
#include<string.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Reading documents
// Locate file pointer
//SEEK_SET
fseek(pf, 2, SEEK_SET);
int ch = fgetc(pf);
printf("%c\n", ch);
printf("%d\n", ftell(pf));
//SEEK_CUR
fseek(pf, 2, SEEK_CUR);
ch = fgetc(pf);
printf("%c\n", ch);
printf("%d\n", ftell(pf));
//SEEK_END
fseek(pf, -1, SEEK_END);
ch = fgetc(pf);
printf("%c\n", ch);
printf("%d\n", ftell(pf));
return 0;
}
rewind
Return the file pointer to the beginning of the file
void rewind ( FILE * stream );
#include<stdio.h>
#include<errno.h>
#include<string.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Reading documents
// Locate file pointer
//SEEK_SET
fseek(pf, 2, SEEK_SET);
int ch = fgetc(pf);
printf("%c\n", ch);
printf("%d\n", ftell(pf));
//SEEK_CUR
fseek(pf, 2, SEEK_CUR);
ch = fgetc(pf);
printf("%c\n", ch);
printf("%d\n", ftell(pf));
//SEEK_END
fseek(pf, -1, SEEK_END);
ch = fgetc(pf);
printf("%c\n", ch);
printf("%d\n", ftell(pf));
//rewind
rewind(pf);
ch = fgetc(pf);
printf("%c\n", ch);
printf("%d\n", ftell(pf));
fclose(pf);
pf = NULL;
return 0;
}
Text files and binaries
According to the organization of data , Data files are called text file perhaps Binary .Data is stored in memory in binary form , If the output without conversion is to external memory , Namely Binary .If it's required to use ASCII In the form of code , You need to convert before storing . With ASCII The file stored in the form of characters is text file .A data in memoryAll characters are written in ASCII stored , Numerical data can be used either ASCII stored , It can also be stored in binary form . If there are integers 10000, If the ASCII Code output to disk , The disk is occupied by 5 Bytes ( One byte per character ), And binary output , On the disk 4 Bytes (VS2013 test )

#include <stdio.h>
int main()
{
int a = 10000;
FILE* pf = fopen("test.txt", "wb");
fwrite(&a, 4, 1, pf);// The binary form is written to the file
fclose(pf);
pf = NULL;
return 0;
}
Determination of the end of file reading
Misused feof
Keep in mind : During file reading , Out-of-service feof The return value of the function is directly used to determine whether the end of the file .It is Apply when the file reading is finished , The judgment is that the read failed and ended , Or end of file .1. Whether the reading of text file is finished , Determine whether the return value is EOF ( fgetc ), perhaps NULL ( fgets )for example :fgetc Judge whether it is EOF .fgets Determine whether the return value is NULL .2. Judgment of reading end of binary file , Judge whether the return value is less than the actual number to be read .for example :fread Judge whether the return value is less than the actual number to be read .
feof
Prototype
int feof ( FILE * stream );
Examples of text files :
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int c; // Be careful :int, Not char, Ask to deal with EOF
FILE* fp = fopen("test.txt", "r");
if(!fp) {
perror("File opening failed");
return EXIT_FAILURE;
}
//fgetc When reading fails or the end of the file is encountered , Will return to EOF
while ((c = fgetc(fp)) != EOF) // standard C I/O Read file cycle
{
putchar(c);
}
// Judge why it ended
if (ferror(fp)) // Determine whether to encounter I/O error
puts("I/O error when reading");
else if (feof(fp))
puts("End of file reached successfully");
fclose(fp);
}Examples of binary files :
#include <stdio.h>
enum { SIZE = 5 };
int main(void) {
double a[SIZE] = {1.,2.,3.,4.,5.};
FILE *fp = fopen("test.bin", "wb"); // Binary mode must be used
fwrite(a, sizeof *a, SIZE, fp); // Write double Array of
fclose(fp);
double b[SIZE];
fp = fopen("test.bin","rb");
size_t ret_code = fread(b, sizeof *b, SIZE, fp); // read double Array of
if(ret_code == SIZE) {
puts("Array read successfully, contents: ");
for(int n = 0; n < SIZE; ++n)
printf("%f ", b[n]);
putchar('\n');
} else { // error handling
if (feof(fp)) // Judge whether to read to the end
printf("Error reading test.bin: unexpected end of file\n");
else if (ferror(fp)) // Determine whether there is a reading error
{
perror("Error reading test.bin");
}
}
fclose(fp);
}File buffer
ANSIC The standard is “ Buffer file system ” Processing of 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 ”. Data output from memory to disk is first sent to a buffer in memory , After the buffer is filled, it is sent to the disk together . If you read data from disk to computer , Then read the data from the disk file and input it into the memory buffer ( Fill the buffer ), And then send the data from the buffer to the program data area one by one ( Program variables, etc ). The size of the buffer depends on C The compiler system decides .
Example
VS2013 WIN10 Environmental testing
#include <stdio.h>
#include <windows.h>
//VS2013 WIN10 Environmental testing
int main()
{
FILE*pf = fopen("test.txt", "w");
fputs("abcdef", pf);// Put the code in the output buffer first
printf(" sleep 10 second - The data has been written , open test.txt file , Found no content in the file \n");
Sleep(10000);
printf(" Refresh buffer \n");
fflush(pf);// When the buffer is flushed , Write the data in the output buffer to a file ( disk )
// notes :fflush In high version VS It can't be used on
printf(" Sleep again 10 second - here , Open again test.txt file , There's something in the file \n");
Sleep(10000);
fclose(pf);
// notes :fclose When closing a file , It also flushes the buffer
pf = NULL;
return 0;
}Run the code and you can see the changes of the data in the file , It passes through the buffer
Here we can get a Conclusion :
Because there is a buffer ,C Language when operating files , You need to flush the buffer or close the file at the end of the file operation .
If you don't do , May cause problems in reading and writing files .
Conclusion
A big cloth wrapped in a thick cloth , The stomach has the poetry book gas from China .
-- The song dynasty · Su shi 《 Leave with Dong Chuan 》
边栏推荐
- Caffe framework and production data source for deep learning
- Su Chunyuan, founder of science and technology · CEO of Guanyuan data: making business use is the key to the Bi industry to push down the wall of penetration
- Preparation of mobile end test cases
- Explain the edge cloud in simple terms | 2. architecture
- After reading this article, I found that my test cases were written in garbage
- 深入浅出边缘云 | 2. 架构
- Usage differences of drop, truncate and delete
- AtCoder Beginner Contest 261E // 按位思考 + dp
- Summary of Baimian machine learning
- The vs compiled application is missing DLL
猜你喜欢

Summary of feature selection: filtered, wrapped, embedded

The server switches between different CONDA environments and views various user processes

Bibliometrix: dig out the one worth reading from thousands of papers!

正则表达和绕过案例

深度学习中的学习率调整策略(1)

Deep learning 1 perceptron and implementation of simple back propagation network

Sword finger offer II 001. integer division

Mysql库的操作
![Rasa 3.x learning series -rasa [3.2.4] - 2022-07-21 new release](/img/1e/27f107d514ded6641410cc5a45764b.png)
Rasa 3.x learning series -rasa [3.2.4] - 2022-07-21 new release
![[matlab] matlab drawing Series II 1. Cell and array conversion 2. Attribute cell 3. delete Nan value 4. Merge multiple figs into the same Fig 5. Merge multiple figs into the same axes](/img/4d/b0ba599a732d1390c5eeb1aea6e83c.png)
[matlab] matlab drawing Series II 1. Cell and array conversion 2. Attribute cell 3. delete Nan value 4. Merge multiple figs into the same Fig 5. Merge multiple figs into the same axes
随机推荐
pytorch with torch.no_grad
Tiger mouth waterfall: Tongliang version of xiaohukou waterfall
Detailed explanation of address bus, data bus and control bus
Data analysis and mining 1
String application - calculate the longest true prefix of a string
使用 Fiddler Hook 报错:502 Fiddler - Connection Failed
Caffe framework and production data source for deep learning
Rasa 3.x learning series -rasa fallbackclassifier source code learning notes
Attributeerror: module 'distutils' has no attribute' version error resolution
Native asynchronous network communication executes faster than synchronous instructions
Not configured in app.json (uni releases wechat applet)
[matlab] matlab drawing Series II 1. Cell and array conversion 2. Attribute cell 3. delete Nan value 4. Merge multiple figs into the same Fig 5. Merge multiple figs into the same axes
The difference and relation among list, set and map
Atcoder beginer contest 261 f / / tree array
TS learning record (I) sudo forgets the password (oolong) try changing the 'lib' compiler option to include 'DOM'
Fraud detection cases and Titanic rescued cases
股票开户之后就可以购买6%的理财产品了?
binlog、iptables防止nmap扫描、xtrabackup全量+增量备份以及redlog和binlog两者的关系
CSDN垃圾的没有底线!
Property datasource is required exception handling [idea]