当前位置:网站首页>C language file operation
C language file operation
2022-06-28 18:59:00 【Jiangxueqian】
C Language file operation
List of articles
What is a document
A file is a segment on a disk Storage space .
The format of different files is different , That is to say, the data stored in the file is different . such as txt( text file ) What is stored is character data ,png( Picture file ) What is stored is color identification data ,exe( Executable file ) All that is stored is code . Of course, the essence of data is binary 0 and 1, Different documents are used on a macro level suffix Distinguishable .
The so-called file operation , Is to read the contents of the file into the program , Then parse according to the format , Read, write, etc .
How to operate files
One 、 Open file
FILE *fopen( const char *filepath, const char *mode );
Use the above function to open a file . Its principle is to open up a piece of physical memory Space , The contents of the selected file on the disk Copy To come over ( The essence is a lot of strings ), And then operate . When we finish working on the file , And then copy this one to update To disk space , Finally complete the modification .
FILE* // The return value is a file pointer , That is, the first address of this space in the physical memory
fopen // Function name
const char *filepath // Parameters 1, Path to file ( absolute 、 Relative paths ), Note the absolute path \ To escape
const char *mode // Parameters 2, How to open the file
When we finish working on the file , Need to be in the program Close file . This step will update our modified file to disk space , Release the memory space of the opened operation file .
int fclose( FILE *stream ); // The only parameter , The file pointer
Two 、 How to open the file
( One ) Text mode ( Default open mode )
r Pattern : read only mode
r Pattern, also called rt (read text) Pattern , Open the file in this way , The documentCan only read , Do not modify .And the prerequisite for opening isThe file must exist, Failed to open if it does not exist , Will report a mistake .w Pattern : Read and write mode from the beginning
w Pattern, also called wt Pattern , adopt w Mode open file , First of all beAutomatically erase the original data. For example, the file originally had content ,w When the mode is turned on, the file will be erased first , Write new data again according to the operation .And when
file does not existWhen , Meetingcreate a file.a Pattern : Read and write mode
a Pattern, also called at Pattern (append), adopt a Mode open file ,Will not erase the original data, But inThe original content is followed by. For example, the file contains contents , Open the file and leave the contents intact , If you write new content , Will continue to write on the original tail .When
file does not existWhen , Meetingcreate a file.Three modes plus edition
r+ Pattern( r Pattern plus edition ), Open the file in this mode ,Can read but write. therefore plus The point is to add“ Write ”operation . Note that the premise is still that the file must exist . and r+ Mode equivalence w Pattern , All erasure and writing .Empathy ,w+ and a+ The pattern is w and a Mode plus edition . because plus The point is to add “ Write ” operation , therefore plus The version is the same as before .
( Two ) Binary mode ( The specified mode is required )
rb Pattern : read only mode
rb(read bit) Pattern, The principle is the same as rt Pattern .( The file must exist )wb Pattern : Read and write mode from the beginning
wb Pattern, The principle is the same as wt Pattern .( If the file does not exist, the file will be created )ab Pattern : Read and write mode
ab Pattern, The principle is the same as ab Pattern .( If the file does not exist, the file will be created )Three modes plus edition
rb+ Pattern( rb Pattern plus edition ), fileCan read but write. Note that the premise is still that the file must exist . and r+ Mode equivalence w Pattern , All erasure and writing .Empathy ,wb+ and ab+ The pattern hasn't changed much .
3、 ... and 、 Operation file
( One ) Write
fwrite: Write the specified number of bytes at a time
size_t fwrite( // The return value is the number of characters actually written (int type ), Write failure will return 0 const void *buffer, // Parameters 1: The first address of the data to be written to the file , Can be a string 、 Array 、 Structure size_t size, // Parameters 2:sizeof( type ) size_t count, // Parameters 3: Number of data , Parameters 2 With the parameters 3 Multiply to get the number of bytes written FILE *stream // Parameters 4: The file pointer );Take a chestnut :
#include <stdio.h> #include <string.h> int main() { char* str = "I LOVE YOU !"; FILE* f = fopen("C:\\Users\\13040\\Desktop\\test.txt", "w"); fwrite(str, sizeof(char), strlen(str), f); fwrite("\n", sizeof(char), 1, f); // Write carriage return fwrite(str, sizeof(char), strlen(str), f); fclose(f); return 0; }fputs: Write one line at a time ( But it doesn't automatically wrap lines , Line feed needs to add... At the end of the input string \n)
int fputs( const char *str, FILE *stream ); // Return value : Successfully returns 0, Failure to return EOF(-1) // Parameters 1: String entered ( Only strings can be entered ) // Parameters 2: The file pointerGive me a plum :
#include <stdio.h> #include <string.h> int main() { char* str = "I LOVE YOU !"; FILE* f = fopen("C:\\Users\\13040\\Desktop\\test.txt", "w"); fputs(str, f); fputs("\n", f); fputs(str, f); fclose(f); return 0; }fprintf: Format write
int fprintf( FILE *stream, // The file pointer const char *format [,// and printf Function requires the same parameters argument ]... );Take a pear :
#include <stdio.h> #include <string.h> int main() { FILE* f = fopen("C:\\Users\\13040\\Desktop\\test.txt", "w"); fprintf(f, "%d,%s,%lf", 12, "hello", 12.34); fclose(f); // Write content :12,hello,12.340000 return 0; }
( Two ) read ( Be careful w and r+ The mode erases the content )
fread(): Read the specified number of bytes at a time
size_t fread( // The return value is the number of bytes actually read void *buffer, // Parameters 1: Our custom character array , The contents read from the file are installed here size_t size, // Parameters 2:sizeof( type ) size_t count, // Parameters 3: Number of data , Parameters 2 With the parameters 3 The multiplication is equal to the number of bytes read FILE *stream // Parameters 4: The file pointer );for instance :
#include <stdio.h> #include <string.h> int main() { char str[15] = { 0 }; FILE* f = fopen("C:\\Users\\13040\\Desktop\\test.txt", "r"); fread(str, sizeof(char), 12, f); puts(str); //I LOVE YOU ! /*while (fread(str, sizeof(char), 1, f)) { printf("%s", str);// I LOVE YOU ! }*/ fclose(f); return 0; }fread() Read write structure :#include <stdio.h> struct Node { int id; char name[10]; short age; double score; }; int main() { // Write operations struct Node stu1 = { 13," Zhang San ",20,88.8 }; FILE* f = fopen("C:\\Users\\13040\\Desktop\\test.txt", "w"); fwrite(&stu1, sizeof(stu1), 1, f); fclose(f); // Read operations struct Node stu2; FILE* g = fopen("C:\\Users\\13040\\Desktop\\test.txt", "r"); fread(&stu2, sizeof(stu1), 1, g); fclose(f); return 0; } // Debugging found :stu2{id=13 name=0x000000af711cfc0c " Zhang San " age=20 ...} Successfully readfgets(): Read one line at a time
char *fgets( char *str, int n, FILE *stream ); // Return value : Namely str The address of // Parameters 1: Where is the data read out // Parameters 2: Maximum reads , Do not exceed the parameters 1 The length of // Parameters 3: The file pointerfor instance :
#include <stdio.h> #include <string.h> int main() { char str[20] = ""; FILE* f = fopen("C:\\Users\\13040\\Desktop\\test.txt", "r"); fgets(str, 20, f); puts(str); fclose(f); return 0; }fscanf(): Format read ( And fprintf Matching use of )
int fscanf( FILE *stream, // The file pointer const char *format [,// and scanf Function requires the same parameters argument ]... );for instance :
#include <stdio.h> #include <string.h> int main() { int a = 0; char str[20] = { 0 }; double b = 0; FILE* f = fopen("C:\\Users\\13040\\Desktop\\test.txt", "r"); // First w Mode writing , Remember that string concatenation numbers must be separated by spaces , Otherwise, the string will not stop when it is read //fprintf(f, "%d,%s %lf", 12, "hello", 12.34); // How to use it? fprintf Written ,fscanf You have to read it , Format strings must be consistent fscanf(f, "%d,%s %lf", &a, str, &b); printf("%d\n", a); printf("%s\n", str); printf("%lf", b); fclose(f); return 0; } /* 12 hello 12.340000 */
( 3、 ... and ) File cursor pointer
In order to control reading and writing , The system sets a file read / write cursor pointer for each file ( Or file read / write position mark ), Used to indicate “ Next to read and write the position of the next character ”.
In general , When reading and writing text files sequentially , The file cursor pointer points to the beginning of the file , At this time, read operation is performed , Read the first character , Then the file cursor pointer moves back one position , And so on , End of file encountered .
If it's a write operation , After each data is written , The file cursor pointer moves backward one position in sequence , Then write the data to the new location at the next write operation , And so on , Until all the data is written .
Or as needed , Manually move the cursor pointer position .
feof Determine whether the cursor pointer of the file is at the end of the file
int feof( FILE *stream ); // The parameter is the file pointer // Return value : The cursor pointer does not reach the end of the file and returns 0, At the end, return to !0( This can be used as a cyclic condition )fseek Set the position of the file cursor pointer
int fseek( FILE *stream, // Parameters 1: The file pointer long offset, // Parameters 2: Set the position of the file cursor pointer int origin // Parameters 3: Specific location );Cancer plum :
fseek(f, 0L, SEEK_SET) // Set the cursor pointer to the starting position of the file fseek(f, 10L, SEEK_SET) // Set the cursor pointer to the starting position towards the right Move 10 Bytes fseek(f, 10L, SEEK_CUR) // Set the cursor pointer to the current position towards the right Move 10 Bytes fseek(f, -10L, SEEK_CUR)// Set the cursor pointer to the current position towards the left Move 10 Bytes fseek(f, 0L, SEEK_END) // Set the cursor pointer to the end of the file ( After the last character ) fseek(f, -10L, SEEK_END)// Set cursor pointer to end towards the left Move 10 Bytesftell Returns the current position of the file cursor pointer
long ftell( FILE *stream // The file pointer ); // Returns the index of the current position of the file cursor pointer ( Subscript from 0 Start )
边栏推荐
- postgresql数据库docker
- A few lines of code can realize complex excel import and export. This tool class is really powerful!
- Modular operation
- Analysis of the core components of mybayis
- 匿名函数this指向以及变量提升
- 抗兔Dylight 488丨Abbkine通用型免疫荧光(IF)工具箱
- C语言指针的一些易错点
- 技术管理进阶——管理者如何做绩效沟通及把控风险
- About Critical Values
- About covariance and correlation
猜你喜欢

About Statistical Distributions

curl: (56) Recv failure: Connection reset by peer

About Critical Values

POI excel conversion tool

Professor Michael Wooldridge of Oxford University: how the AI community views neural networks in the past 40 years

About Critical Values

C# 41. Int to string

First day of new work

打破学科之间壁垒的STEAM教育

Memory leak
随机推荐
Understanding of closures
【C#】详解值类型和引用类型区别
技术管理进阶——管理者如何做绩效沟通及把控风险
解析机器人主持教学的实践发展
Shell script batch modify file directory permissions
19.2 容器分类、array、vector容器精解
About Statistical Distributions
Object tracking using tracker in opencv
C语言文件操作
openGauss内核:SQL解析过程分析
memory thrashing
Baidu time factor addition
sql面试题:求连续最大登录天数
毕业设计-基于Unity的餐厅经营游戏的设计与开发(附源码、开题报告、论文、答辩PPT、演示视频,带数据库)
Professor Michael Wooldridge of Oxford University: how the AI community views neural networks in the past 40 years
Native implementation Net5.0+ custom log
pd.cut 区间参数设定之前后区别
中金财富开户安全吗?开过中金财富的讲一下
SqlTransaction
手动备份和还原DHCP服务器