当前位置:网站首页>C language file operation
C language file operation
2022-06-11 00:03:00 【ღ ° Jiusan ฅ ՞】
List of articles
- One 、 Opening and closing of files
- Two 、 Sequential reading and writing of files
- fgetc And fputc
- fgets And fputs
- fscanf And fprintf
- Code demonstration
- Comparison of a set of functions
- printf( Print data to the screen )
- scanf( Get data from the keyboard )
- fprintf( Print data to a file ,stream = stdout when , amount to printf)
- fscanf( Get data from files ,stream = stdin when , amount to scanf)
- sprintf( Convert data to strings )
- sscanf( Converts the contents of a string to a specified format )
- sscanf And sprintf Code demonstration
- fread And fwrite
- 3、 ... and 、 Random reading and writing of documents
- Four 、 Simple comparison between text file and binary file
- 5、 ... and 、 Misused feof
- 6、 ... and 、 File buffer
One 、 Opening and closing of files
FILE * fopen ( const char * filename, const char * mode );—> Open file , The second parametermodeIt's read-write mode- After use , You also need to close the file :
int fclose ( FILE* stream);
#include <stdio.h>
int main ()
{
FILE * pFile;
// Open file
pFile = fopen ("myfile.txt","w");
if (pFile==NULL)
{
// fail to open file , Unable to operate
printf("pFile is fail\n");
return 0;
}
// pFile Successfully point to a valid file information area , File operation is available
fputs ("fopen example",pFile);
// Close file
fclose (pFile);
return 0;
}
Common reading and writing modes mode
| Pattern | meaning | If the specified file does not exist |
|---|---|---|
| “r”( read-only ) | To enter data , Open one Already exist Text file for | error |
| “w”( Just write ) | To output data , Open a text file | Automatically create files |
| “a”( Additional ) | Append data to the end of the text file | Automatically create files |
| “rb”( read-only ) | To enter data , Open a binary file | error |
| “wb”( Just write ) | To enter data , Open a binary file | Automatically create files |
| “ab”( Additional ) | Add data to the end of a binary file | error |
Two 、 Sequential reading and writing of files
All flows : Handle file out of stream , The computer will open three streams by default every time it is turned on and running , It is called standard flow .
- stdout - Standard output stream
- stdin - Standard input stream
- stderror - Standard error flow
fgetc And fputc
- fgetc -
characterInput function , For all streamsint fgetc( FILE *stream ); - fputc -
characterOutput function , For all streamsint fputc( int c, FILE *stream );
Code display
// fgetc And fputc
int main()
{
// Open file
FILE* pf = fopen("data.txt", "r");
if (pf == NULL)
{
// Open the failure
printf("%s\n", strerror(errno));
return 0;
}
// Working with files
/*int ch = 'a'; for (ch = 'a'; ch <= 'z'; ch++) { fputc(ch, pf); }*/
for (int i = 0; i < 26; i++)
{
int ch = fgetc(pf);
printf("%c", ch);
}
printf("\n");
// Close file
fclose(pf);
return 0;
}
fputc take 26 Write a letter to the file 
fgetc Read character by character in the file 
fgets And fputs
Be careful : When I was studying, I always thought fputs Is to write a sentence on one line , and fgets Read a line ; Actually fputs It's direct writing , and fgets It is on demand , The number of incoming reads is required
- fgets - Text line input function , For all streams
char *fgets( char *string, int n, FILE *stream );- The return is string The address of ( From a stream Read in the stream n Characters to string in ) - fputs - Text line output function , For all streams
int fputs( const char *string, FILE *stream );( Write a string to stream In the stream )
Code display
// fgets And fputs
int main()
{
// Open file
FILE* pf = fopen("data.txt", "r");
if (pf == NULL)
{
// Open the failure
printf("%s\n", strerror(errno));
return 0;
}
// Working with files
/*fputs("hello world\n", pf); fputs("I Love You\n", pf);*/
char arr[100] = {
0 };
fgets(arr,10,pf);
printf("%s\n", arr);
// Close file
fclose(pf);
return 0;
}
fputs - Write two sentences 
fgets - Reading data 
fscanf And fprintf
For formatted input and output
- fscanf - Format input function , For all streams
int fscanf( FILE *stream, const char *format [, argument ]... ); - fprintf - Format output function , For all streams
int fprintf( FILE *stream, const char *format [, argument ]...);
Code demonstration
// fprintf And fscanf
struct Stu
{
char name[20];
int age;
};
int main()
{
struct Stu s = {
"chen", 20 };
struct Stu tmp = {
0 };
FILE* pf = fopen("data.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
//fprintf(pf,"%s %d\n", s.name, s.age);
fscanf(pf, "%s %d", tmp.name, &(tmp.age));
printf("%s %d\n", tmp.name, tmp.age);
fclose(pf);
return 0;
}
fprintf - Output a structure data to a file according to the format

fscanf - Input the data in the file into the structure in a formatted form

Comparison of a set of functions
printf( Print data to the screen )
int printf( const char *format [, argument]... );- towards stdout Function to format the output
scanf( Get data from the keyboard )
int scanf( const char *format [,argument]... );- from stdin Format the input function
fprintf( Print data to a file ,stream = stdout when , amount to printf)

fscanf( Get data from files ,stream = stdin when , amount to scanf)

sprintf( Convert data to strings )

sscanf( Converts the contents of a string to a specified format )

sscanf And sprintf Code demonstration
struct Book
{
char name[20];
double price;
};
int main()
{
struct Book book = {
"C Programming ", 66.6 };
struct Book tmp = {
0 };
char arr[100] = {
0 };
sprintf(arr, "%s %lf", book.name, book.price);
printf("%s\n", arr);
sscanf(arr, "%s %lf", tmp.name, &(tmp.price));
printf("%s %lf\n", tmp.name, tmp.price);
return 0;
}

fread And fwrite
- fread - Binary input ,
Only for filessize_t fread( void *buffer, size_t size, size_t count, FILE *stream );- take stream The contents of the file stream are input into buffer In the variable at address , Every time you type count individual size The contents of the number of bytes ; Return value : The number of contents actually written ( It also uses a number to judge whether it is over ) - fwrite - Binary output ,
Only for filessize_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );- take buffer The content at the address is entered into stream In file stream , Every time you type count individual size The contents of the number of bytes ; Return value : The number of contents actually output to the file ( It also uses a number to judge whether it is over )
Code display
// fread And fwrite
#include <stdio.h>
int main()
{
int a = 10000;
int c = 0;
FILE* pf = fopen("test.txt", "rb");
if (pf == NULL)
return 0;
// fwrite(&a, 4, 1, pf);// The binary form is written to the file
fread(&c, 4, 1, pf);
printf("%d\n", c);
fclose(pf);
pf = NULL;
return 0;
}
fwrite
fread
3、 ... and 、 Random reading and writing of documents
fseek
according to
The position of the file pointerandOffsetTo locate the file pointer
int fseek ( FILE * stream, long int offset, int origin );- offset - Offset ( Positive numbers go backwards , Negative numbers go forward )
- origin - The starting position of the file offset
- SEEK_CUR - Current pointer position
- SEEK_END - end of file
- SEEK_SET - Beginning of file

ftell
Returns the offset of the file pointer from its starting position
long int ftell ( FILE * stream );

rewind
Return the file pointer to the beginning of the file
void rewind ( FILE * stream );- Same effect fseek Realization :
fseek(FILE * stream,0,SEEK_CUR);

Four 、 Simple comparison between text file and binary file
All characters are written in ASCII stored , Numerical data can be used either ASCII stored , It can also be stored in binary form . The following will demonstrate with numerical data storage
- Binary : Data is stored in memory in binary form , If the output without conversion is to external memory
- text file : If it's required to use ASCII In the form of code , You need to convert before storing . With ASCII Characters in the form of stored files
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 ).
Binary storage
int main()
{
int a = 10000;
FILE* pf = fopen("test.txt", "wb");
if (pf == NULL)
return 0;
fwrite(&a, 4, 1, pf); // Write to file in binary form
fclose(pf);
pf = NULL;
return 0;
}



File store
The contents are directly displayed as integers 10000
5、 ... and 、 Misused feof
int feof( FILE *stream );- feof() Is a function that detects the file terminator on the stream , If the file ends , Then return to non 0 value , Otherwise return to 0
Be careful :feof It is not used to judge whether the file is finished , But to judge why it ended (1. Read failed ,2. Read to the end of the file )
text file
- Whether the reading of text file is finished , Determine whether the return value is EOF ( fgetc ), perhaps NULL ( fgets )
int main()
{
int c; // Be careful : To judge EOF, Need to use int
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("File opening failed");
return 0;
}
//fgetc When reading fails or the end of the file is encountered , Will return to EOF
while ((c = fgetc(pf)) != EOF)
{
fputc(c, stdout);
}
// Judge why it ended
if (feof(pf))
{
printf("End of file reached successfully");
}
else
{
printf("error when reading");
}
fclose(pf);
pf = NULL;
return 0;
}
Binary
#include <stdio.h>
int main()
{
int a = 10000;
int c = 0;
FILE* pf = fopen("test.txt", "rb");
if (pf == NULL)
return 0;
while (fread(&c, 4, 1, pf))
{
printf("%d\n", feof(pf));
}
printf("%d\n", feof(pf));
if (feof(pf))
printf("End of file reached successfully\n");
else
printf("error when reading\n");
fclose(pf);
pf = NULL;
return 0;
}

6、 ... and 、 File buffer
What is a file buffer
ANSIC The standard puts forward “ File buffer system ”, The so-called buffered file system means that the system automatically creates files for programs in memory Open up a block for each file in use “ 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 memory Impact area ( Fill the buffer ), And then send the data from the buffer to the program data area one by one ( Program variables, etc ). Before full , Flusheable buffer , Let it force output , Input .
The size of the buffer is designed by the compiler vendor

- Be careful : stay Linux The buffer effect can be better seen in
#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;
}
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 Pieces of . If you don't do , May cause problems in reading and writing files .
The meaning of the buffer
- Process the instructions entered by the user together Than Character by character processing Less consumption
- When the user is typing , Input error , Changeable , Enter and execute , Better user experience
Buffer classification
C Languages use different buffers in different places as needed .
Buffers are divided into two categories : Completely buffered I/O And line buffering I/O And without buffering .
(1) Full buffering means that the buffer is refreshed only when the current buffer is full ( The content is sent to the destination ), It usually appears in file input . The size of the buffer depends on the system , The common size is 512 Byte and 4096 byte .
(2) Line buffering refers to refreshing the buffer when a line break occurs . Keyboard input is usually line buffered input , So press Enter Key to refresh the buffer . A common example is getchar() function , When the program calls getchar() Function time , The program is waiting for the user to press the button , The characters entered by the user are stored in the keyboard buffer , Until the user presses enter ( The carriage return character is also placed in the buffer ). When the user types enter ,getchar() Function starts reading one character at a time from the keyboard buffer . in other words , Follow up getchar() Function calls do not wait for the user to press a key , And read the characters in the buffer directly , Until the characters in the buffer are read , Just wait for the user to press the key again . When the buffer is full, it will not be refreshed automatically and input cannot continue , Press enter to refresh the buffer .
(3) Without buffer : Standard output without buffer ( for example :cerr
(4) Buffer refresh ( Carry out the real I/O operation )
When the buffer is full : perform flush sentence ; perform end sentence ; Close file .
边栏推荐
- Four ways to add names to threads in the thread pool
- Redis installation and common problem solving based on centeros7 (explanation with pictures)
- Easyrecovery15 simple and convenient data recovery tool
- Error 1046 when LabVIEW uses MathScript node or matlab script
- 给线程池里面线程添加名称的4种方式
- 2022 college entrance examination quantitative paper | please answer the questions for quantitative candidates
- High speed data stream disk for LabVIEW
- [pyGame] can the little dinosaur on chrome be played with code? It looks like fun~
- LabVIEW displays the time and date on the waveform chart or waveform chart
- 快速排序
猜你喜欢

LabVIEW调用DLL时出现异常0xc0000005代码

【Pygame小游戏】这款经典的炸弹人超能游戏上线,你爱了嘛?(附源码)
![[pyGame games] in the first month, it broke 100 million to download a masterpiece that is highly integrated with](/img/f5/d947f5e5c2abf79c0fac2f45103ec0.png)
[pyGame games] in the first month, it broke 100 million to download a masterpiece that is highly integrated with "super casual game features"~

LabVIEW或MAX下的VISA测试面板中串口无法工作
![[pyGame games] here it is. This Gobang game is super A. share it with your friends~](/img/76/faea3558ed6fadff755c517922088b.png)
[pyGame games] here it is. This Gobang game is super A. share it with your friends~

【Pygame小游戏】激荡大脑思维,一起来玩转奇思妙想“24点”叭~(超赞滴)
![[pyGame games] interesting puzzle game: how many hamsters can you play? (source code attached)](/img/88/733cddca32491c4ac45102aa703815.jpg)
[pyGame games] interesting puzzle game: how many hamsters can you play? (source code attached)
![[auto reply Script] happy new year. I typed every word myself, not forwarded it~](/img/53/75d2bbbee653a41e206ebd751fdea1.png)
[auto reply Script] happy new year. I typed every word myself, not forwarded it~

30 | how to reset the consumer group displacement?

【Pygame小游戏】Chrome上的小恐龙竟可以用代码玩儿了?它看起来很好玩儿的样子~
随机推荐
LabVIEW错误“内存已满 - 应用程序停止在节点”
LabVIEW锁相环(PLL)
LabVIEW获取Clamp函数找到的所有点的信息
LabVIEW用高速数据流盘
【Pygame合集】滴~穿越童年游戏指南 请查收:这里面有你玩过的游戏嘛?(附五款源码自取)
【Turtle表白合集】“海底月是天上月,眼前人是心上人。”余生多喜乐,长平安~(附3款源码)
LabVIEW get IMAQ get last event coordinates
Deepin20菜单启动选项后自检到iwlwifi停机
[pyGame games] story stream recommendation: what kind of games can you like? (devil lover, bully's wife version)
What is the workflow of dry goods MapReduce?
[pyGame] when the "coolest snake in history" arrives, fun will play it (no money for fun)
【Pygame小游戏】“史上最炫酷贪吃蛇”驾到,FUN开玩(不好玩不要钱)
Easyrecovery15 simple and convenient data recovery tool
IGBT and third generation semiconductor SiC double pulse test scheme
csdn每日一练——有序表的折半查找
安全生产月,黄埔开展燃气安全进商铺宣传活动
[fireworks in the sky] it's beautiful to light up the night sky with gorgeous fireworks. A programmer brought a fireworks show to pay New Year's greetings to everyone~
[pyGame games] tank battle, how many childhood games do you remember?
Four ways to add names to threads in the thread pool
Apple CMS collection station source code - building tutorial - attached source code - new source code - development documents