当前位置:网站首页>C language file operation
C language file operation
2022-04-23 06:21:00 【Clear and white】
file type
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 .
Data flow
Just C In terms of procedure , Move from program to , Remove byte , This byte stream is called stream . The interaction between program and data is in the form of flow . Conduct C When reading and writing language files , We'll do it first “ Open file ” operation , This operation is to open the data stream , and “ Close file ” The operation is to close the data flow .
File buffer
ANSIC The standard is “ Buffer file system ” Processing of data files , The so-called buffered file system refers to that the system automatically stores data in memory for each file in the program
Use the file to open up a piece “ File buffer ”. Data output from memory to disk is first sent to a buffer in memory , The buffer is filled before it is sent to disk
On . 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 ), Then from the buffer
Send data to the program data area ( Program variables, etc ). The size of the buffer depends on C The compiler system decides .

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 , Document status and
The current location of the file, etc ). This information is stored in a structure variable . The structure type is system declared , The name FILE.
for example ,VS2008 The compiler environment provides stdio.h The header file has the following file type declaration :
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;
Every time you open a file , The system will automatically create a FILE Structural variables , And fill in the information .
It's usually through a FILE To maintain this FILE Structural variables , This is more convenient to use .
Now we can create a FILE* Pointer variable for :
FILE* pf// The file pointer
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 this article
The information in the file information area 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
Files should be read and written first Open file , After use, you should Close file .
fopen
Open file
The function prototype :
FILE *fopen( const char *filename, const char *mode );
- filename File name ,mode It's the way to open a file
Open it as follows :
| 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 | error |
| “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 |
Take a chestnut :
/* fopen fclose example */
#include <stdio.h>
int main ()
{
FILE * pFile;
pFile = fopen ("myfile.txt","w");
if (pFile!=NULL)
{
fputs ("fopen example",pFile);
fclose (pFile);
}
return 0;
}
fclose
Close file
The function prototype :
int fclose( FILE *stream );
- stream Is a file pointer to the file opened with
Sequential reading and writing of files
| 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
Read character
The function prototype :
int fgetc( FILE *fp);
- from fp Read a character in , Return as return value
fputc
Write characters
The function prototype :
int fputc( int c, FILE *stream );
- c It's an integer variable , The character to write to the file
- stream: The file pointer , Files to write
fgets
Read string
The function prototype :
char * fgets ( char * str, int num, FILE * stream );
- str: Accept the memory address of the string , It can be an array alias , It can also be a pointer
- n: Indicate the number of characters to read
- stream: This is the file pointer , Indicates the file from which to read characters
fputs
Write string
The function prototype :
int fputs( const char *string, FILE *stream );
- str: The string to be written to the file , Not including the last '\0'
- stream: This is the file pointer , Pointer to the file to which the string is to be written
fscanf
Format input
The function prototype :
int fscanf( FILE *stream, const char *format [, argument ]... );
- stream: This is the file pointer
- format: This is a character pointer to a string , The string contains the format of the data to be written , So the string becomes a format string
- argument: Is the variable table column to write to the file , The variables are separated by commas .
fprintf
Format output
The function prototype :
int fprintf( FILE *stream, const char *format [, argument ]...);
- stream: This is the file pointer
- format: This is a character pointer to a string , The string contains the format of the data to be written , So the string becomes a format string
- argument: Is the variable table column to write to the file , The variables are separated by commas .
fread
Binary input
The function prototype :
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
- ptr: Target memory block
- size: The size of bytes read at a time
- count: How many are read at a time size
- stream: The file pointer
fwrite
Binary output
The function prototype :
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
- ptr: Target memory block
- size: The size of bytes read at a time
- count: How many are read at a time size
- stream: The file pointer
Random reading and writing of documents
fseek
Locate the file pointer according to its position and offset .
The function prototype :
int fseek ( FILE * stream, long int offset, int origin );
Take a chestnut :
#include <stdio.h>
int main ()
{
FILE * pFile;
pFile = fopen ( "example.txt" , "wb" );
fputs ( "This is an apple." , pFile );
fseek ( pFile , 9 , SEEK_SET );
fputs ( " sam" , pFile );
fclose ( pFile );
return 0;
}
ftell
Returns the offset of the file pointer from its starting position
The function prototype :
long int ftell ( FILE * stream );
Take a chestnut :
#include <stdio.h>
int main ()
{
FILE * pFile;
long size;
pFile = fopen ("myfile.txt","rb");
if (pFile==NULL)
perror ("Error opening file");
else
{
fseek (pFile, 0, SEEK_END); // non-portable
size=ftell (pFile);
fclose (pFile);
printf ("Size of myfile.txt: %ld bytes.\n",size);
}
return 0;
}
rewind
Return the file pointer to the beginning of the file
The function prototype :
void rewind( FILE *stream );
Take a chestnut :
#include <stdio.h>
int main ()
{
int n;
FILE * pFile;
char buffer [27];
pFile = fopen ("myfile.txt","w+");
for ( n='A' ; n<='Z' ; n++)
fputc ( n, pFile);
rewind (pFile);
fread (buffer,1,26,pFile);
fclose (pFile);
buffer[26]='\0';
puts (buffer);
return 0;
}
End of file decision
feof
The function prototype :
int feof(FILE *fp)
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 .
- 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. - 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 .
Take a chestnut :
#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))
puts("I/O error when reading");
else if (feof(fp))
puts("End of file reached successfully");
fclose(fp);
}
版权声明
本文为[Clear and white]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220531398965.html
边栏推荐
- Practical operation - Nacos installation and configuration
- 2. Average length of words
- Gaussian processes of sklearn
- Contrôle automatique (version Han min)
- 线代第四章-向量组的线性相关
- Use Matplotlib. In Jupiter notebook Pyplot server hangs up and crashes
- 10.Advance Next Round
- 8. Integer Decomposition
- Collections multiple parameter sorting
- Delete and truncate
猜你喜欢

線性代數第一章-行列式
![去噪论文阅读——[CVPR2022]Blind2Unblind: Self-Supervised Image Denoising with Visible Blind Spots](/img/fd/84df62c88fe90a73294886642036a0.png)
去噪论文阅读——[CVPR2022]Blind2Unblind: Self-Supervised Image Denoising with Visible Blind Spots
![Paper on Image Restoration - [red net, nips16] image restoration using very deep revolutionary encoder decoder networks wi](/img/1b/4eea05e2634780f45b44273d2764e3.png)
Paper on Image Restoration - [red net, nips16] image restoration using very deep revolutionary encoder decoder networks wi
![Comparative study paper - [Moco, cvpr2020] momentum contract for unsupervised visual representation learning](/img/21/4bc94fe29f416c936436c04fc16fa8.png)
Comparative study paper - [Moco, cvpr2020] momentum contract for unsupervised visual representation learning

Automatic control (Han min version)

编程记录——图片旋转函数scipy.ndimage.rotate()的简单使用和效果观察

A general U-shaped transformer for image restoration
Best practices for MySQL storage time

container

深入理解去噪论文——FFDNet和CBDNet中noise level与噪声方差之间的关系探索
随机推荐
Pytorch learning record (XII): learning rate attenuation + regularization
Algèbre linéaire chapitre 2 - matrice et son fonctionnement
The problem that the page will refresh automatically after clicking the submit button on the form is solved
Unsupervised denoising - [tmi2022] ISCL: dependent self cooperative learning for unpaired image denoising
程序设计训练
sklearn之 Gaussian Processes
You cannot access this shared folder because your organization's security policy prevents unauthenticated guests from accessing it
Example of ticket selling with reentrant lock
治療TensorFlow後遺症——簡單例子記錄torch.utils.data.dataset.Dataset重寫時的圖片維度問題
Supply chain service terms
Exception handling: grab and throw model
In depth source code analysis servlet first program
Kibana search syntax
Pytorch introduction notes - use a simple example to observe the output size of each layer of forward propagation
The user name and password of users in the domain accessing the samba server outside the domain are wrong
20 excellent plug-ins recommended by idea
Illustrate the significance of hashcode
LDCT图像重建论文——Eformer: Edge Enhancement based Transformer for Medical Image Denoising
Viewer: introduce MySQL date function
Pytorch notes - observe dataloader & build lenet with torch to process cifar-10 complete code