当前位置:网站首页>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 )
边栏推荐
- leetcode 1647. Minimum deletions to make character frequencies unique
- 深入解析kubernetes中的选举机制
- 【Unity3D】发射(RayCast)物理射线(Ray)
- Can I open an account today and buy shares today? Is it safe to open an account online?
- 深入解析kubernetes中的选举机制
- use. NETCORE's own background job, which simply simulates producers and consumers' processing of request response data in and out of the queue
- 获取当前日期0点及23点59时间戳
- C# 41. int与string互转
- 浅谈软件研发的复杂性与效能提升之道
- Shell脚本批量修改文件目录权限
猜你喜欢

微软独家付费功能,也被完美解锁了

Record an emotet Trojan horse handling case

怎样去除DataFrame字段列名

MindSpore系列一加载图像分类数据集

Cvpr2022 | Zhejiang University and ant group put forward a hierarchical residual multi granularity classification network based on label relation tree to model hierarchical knowledge among multi granu

【C#】详解值类型和引用类型区别

About Significance Tests

被315点名的流氓下载器,又回来了…

Mybayis之核心主件分析

leetcode 1423. Maximum points you can obtain from cards
随机推荐
Win 10创建一个gin框架的项目
POI Excel转换工具
leetcode 1647. Minimum Deletions to Make Character Frequencies Unique(所有字母频率不同的最小删除次数)
sql计算每日新增用户、及留存率指标
数字化转型的1个目标,3大领域,6大因素和9个环节
基于管线的混合渲染
Openfire 3.8.2集群配置
Opengauss kernel: analysis of SQL parsing process
Qt 中 QObjectCleanupHandler 使用总结
Record an emotet Trojan horse handling case
【Unity3D】发射(RayCast)物理射线(Ray)
leetcode 1647. Minimum deletions to make character frequencies unique
POI excel conversion tool
PostgreSQL database docker
OpenHarmony—内核对象事件之源码详解
ANR Application Not Responding
浅谈软件研发的复杂性与效能提升之道
正版ST-link/V2 J-LINK JTAG/SWD引脚定义和注意事项
[unity3d] camera follow
leetcode 1423. Maximum points you can obtain from cards