Linux: fopen, fclose, fread, fwrite are simple and practical

Purpose:

Create an empty file bit, and test.c, use fopen, fclose, fread, fwrite and other functions in test.c to read and write "Linux so easy" in the bit file

step

1: Create bit and test

touch bit
touch test.c

2: Write test.c

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 int main()
  4 {
  5   FILE *pf;//创建一个FILE类型的指针
  6   pf=fopen("./bite","r+");//fopen(路径+打开方式)
  7   char str[]="linux so easy";//想要输入的话语
  8   fwrite(str,1,sizeof(str),pf);//fwrite(想要输入指针名+输入的字符大小+总输入的大小+创建的FILE类型指针名)
  9   fread(str,1,sizeof(str),pf);//同理
 10   printf("成功读取");                                                                                                                                                                  
 11   fclose(pf);
 12 }

3: Effect

 

Attachment: several reading and writing methods about fread

r Opens the file read-only, the file must exist.
r+ Open the file in a read-write mode. The file must exist.
w Open the write-only file. If the file exists, the file length will be cleared to 0, that is, the content of the file will disappear. Create the file if it does not exist.
w+ opens a readable and writable file. If the file exists, the file length is cleared to zero, that is, the content of the file will disappear. Create the file if it does not exist. (Common)
rb+ read-write Opens a binary file, allowing data to be read.
a Opens the write-only file as an append. If the file does not exist, it will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be retained.
a+ Opens the file for reading and writing in an additional way. If the file does not exist, it will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be retained.
wb Open or create a new binary file for writing only; only write data is allowed.
wb+ read-write Open or create a binary file, allowing reading and writing.
ab+ read-write Opens a binary file, allowing data to be read or appended to the end of the file.
 

Guess you like

Origin blog.csdn.net/qq_62718027/article/details/128448868