当前位置:网站首页>File operation (detailed!)
File operation (detailed!)
2022-07-02 11:48:00 【Less debug every day】
Indexes
file
1, What is a document
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 output content file
In the past, input refers to input from the keyboard , Output refers to display on the screen ,
But sometimes we output information to disk , When necessary, read the data from the disk to the memory for use , What we are dealing with here is the files on the disk
2, The file pointer FILE
seeing the name of a thing one thinks of its function : Through the file pointer variable, you can find the file associated with it .
stay vs2013 Yes FILE Have the following statement
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;
Different compilers for FILE The definition of is different , But it's the same , Every time we open a file , The system will automatically create a FILE Structural variables , And supplement the information , Generally, we use file pointers to perform relevant operations on files .
3, Opening and closing of files
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 |
// Open file
FILE * fopen ( const char * filename, const char * mode );
The first parameter : Open file name
The second parameter : Open mode , Must be a double quotation mark , Single quotation marks don't work
// Close file
int fclose ( FILE * stream );
Each time you open a file, you only need to write the corresponding opening method .
eg:
// Open the file as a write
FILE* pf = fopen("text.txt", "w");// To output data , Open a text file
// If the asking price doesn't exist, create a new document
// If the file exists, eliminate the original contents in the file
if (pf == NULL)
{
printf(" fail to open file \n");
printf("%s\n", strerror(errno));// Print error messages related to file opening failure
return 0;
}
fclose(pf);
pf = NULL;// Be sure to leave the file empty after closing , Otherwise, wild pointers may appear
When you open the same folder, a
Open file
FILE* pf = fopen("text.txt", "r");// Only existing files can be opened , If it does not exist , Then return to NULL
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
fclose(pf);
Other opening methods are similar
4, Sequential reading and writing of files
The reading of file data can be divided into Sequential reading and writing , Random, speaking, reading and writing , Sequential read-write, as the name suggests, is to write and read files in the order we input and output , Random reading and writing is just random reading and writing in a sense , What is it? Let's see below .
function Function name Apply to | |
Character input function fgetc All input streams | |
Character output function fputc All output streams | |
Text line input function fgets All input streams | |
Text line output function fputs All output streams | |
Format input function fscanf All input streams | |
Format output function fprintf All output streams | |
Binary input fread file | |
Binary output fwrite file |
fgetc,fputc
fputc:int fputc( int c, FILE stream ); Output a character to the stream
c: Indicates that the characters entering the stream need to be read
stream: flow
fputc Applicable to all streams ? What does it mean ?
Take the output as an example : At present, what I know about the output is two streams , Does it flow to the screen or to the file .
Flow can be compared to water , Then the screen and file are in two directions , The direction refers to which direction the water flows, so the data is input or output to .
When running a program from a language , Three streams are opened by default :
Standard input stream :stdin
Standard output stream :stdout These three streams The types of FILE
Standard error flow :stderr
for example :
printf: Standard output stream :stdout( Flow to screen )
scanf: Standard output stream :stdout( keyboard )
fgetc:int fgetc( FILE *stream ); Read characters from the stream into memory , And return the read characters
FILE* pf = fopen("data.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
int ch = 0;
//while ((ch = fgetc(stdin)) != EOF)// When the error or the end of the file is returned EOF
while ((ch = fgetc(pf)) != EOF)// When the error or the end of the file is returned EOF
{
printf("%c ", ch);
}
fputs,fgets
fputs:int fputs( const char *string, FILE *stream );
string: The string to be read
streat: The stream to which the string should flow
Return value : If executed successfully , These functions will return a non negative value . When something goes wrong ,fputs return EOF
fgets:char *fgets( char *string, int n, FILE *stream );
string: The data extracted from the stream is roughly stored in the string
n:fgets Read characters from the current position of the stream , Including the first line break , Read to the end of the stream , Or until the number of characters read is equal to n - 1, Stored at the end of the character will automatically add a ’\0’
stream: Which stream to extract data from
fscanf ,fprint
fread/fwrite
size_t fread( void *buffer, size_t size, size_t count, FILE *stream );
Return value : Returns the number of completed entries actually read
buffer: The entries read from the stream are stored in buffer in
size: The overall size of each read ( In bytes )
count: The maximum number of entries read
stream: Read the source of the entry , It's from the standard input stream ( keyboard ) Or file input
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );
Return value : Returns the number of complete entries successfully written to the stream
size: The size of each entry written
count: Maximum number of entries written
stream: Same as fread
feof/ferror
int main()
{
FILE* pf = fopen("data,txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
int ch = 0;
//fgetc When reading fails or the end of the file is encountered , Will return to EOF
while ((ch = fgetc(pf)) != EOF);// Label read file operation cycle
// Judge what caused it
if (ferror(pf))// If there is no error on the stream ,ferror return 0. otherwise , It returns a non-zero value .
puts("I/O error when reading");
else if (feof(pf))//eof Function returns a non-zero value after the first read operation attempts to read to the end of the file .
// If the current location is not at the end of the file , Then return to 0.
puts("End of file reached successfully");
fclose(pf);
return 0;
}
边栏推荐
- 揭露数据不一致的利器 —— 实时核对系统
- Basic usage of MySQL in centos8
- Visualization of chip SEQ data by deeptools
- PowerBI中导出数据方法汇总
- excel表格中选中单元格出现十字带阴影的选中效果
- 通讯录的实现(文件版本)
- 【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
- 预言机链上链下调研
- II Stm32f407 chip GPIO programming, register operation, library function operation and bit segment operation
- Digital transformation takes the lead to resume production and work, and online and offline full integration rebuilds business logic
猜你喜欢
2022年4月17日五心红娘团队收获双份喜报
map集合赋值到数据库
Jinshanyun - 2023 Summer Internship
Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer
PowerBI中导出数据方法汇总
CTF record
动态内存(进阶四)
Redis exceeds the maximum memory error oom command not allowed when used memory & gt; ' maxmemory'
ren域名有价值吗?值不值得投资?ren域名的应用范围有哪些?
K-Means Clustering Visualization in R: Step By Step Guide
随机推荐
2022年遭“挤爆”的三款透明LED显示屏
Develop scalable contracts based on hardhat and openzeppelin (II)
电脑无缘无故黑屏,无法调节亮度。
Some suggestions for young people who are about to enter the workplace in the graduation season
The selected cells in Excel form have the selection effect of cross shading
Is the stock account given by qiniu business school safe? Can I open an account?
How to Visualize Missing Data in R using a Heatmap
HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
Mmrotate rotation target detection framework usage record
Is the Ren domain name valuable? Is it worth investing? What is the application scope of Ren domain name?
Installation of ROS gazebo related packages
RPA advanced (II) uipath application practice
八大排序汇总
How to Easily Create Barplots with Error Bars in R
ROS lacks xacro package
Thesis translation: 2022_ PACDNN: A phase-aware composite deep neural network for speech enhancement
数字化转型挂帅复产复工,线上线下全融合重建商业逻辑
ROS lacks catkin_ pkg
JS -- take a number randomly from the array every call, and it cannot be the same as the last time
Webauthn - official development document