当前位置:网站首页>Using files to save data (C language)

Using files to save data (C language)

2022-04-23 17:55:00 Chshyz

Save data to a local file

Environmental Science :CentOS7
Common file operation functions and function tables are attached
file extension
.doc(Word file )、.txt( text file )、.dat( Data files )、.c(C Language source file )、.cpp(C++ Source program files )、.for(FORTRAN Language source file )、.pas(Pascal Language source file )、.obj( Target file )、.exe( Executable file )、.ppt( Electronic document slide )、.bmp( Graphic files )、.jpg( image file ).

file type

  • Program files ( Executable )
  • Data files (ASCII Files and binaries )
    ①ASCII file : text file , Each byte stores one character ASCII Code ( Character 、 Numerical type ).
    ② Binary : Output the data in the memory as it is to the disk for storage ( Numerical type ).
    Example : Input 10000
    ASCII Output to disk as (5 byte )
    Output to disk in binary form (2 byte )

The file pointer
Each used file opens up a corresponding file information area in memory to store file related information . There is a structure variable for this information (FILE) in .
example :FILE * fp

Open and close files

  • Open data file (fopen)
    fopen ( file name , Use file mode );
    example :
    FILE * fp; # Define a file that points to a variable fp
    fp = fopen (“a”, “r”); # take fopen The return value of the function is assigned to fp
  • Close file (fclose)
    fclose ( The file pointer )
    example :fclose (fp);

PS:

Use Meaning
r read-only (ASCII file )
w Just write (ASCII file )
a Additional ( towards ASCII Add data at the end of the file )
rb read-only ( Binary )
wb Just write ( Binary )
ab Additional ( Add data to the end of the binary file )
r+ Reading and writing ( Open one ASCII File read and write )
w+ Reading and writing ( Build a new one ASCII file )
a+ Reading and writing (ASCII file )
rb+ Reading and writing ( Binary )
wb+ Reading and writing ( Binary )
ab+ Reading and writing ( Binary )

Example 1: The input is sent to disk

#include <stdio.h>
#include <stdlib.h>
int main() {
    
    FILE * fp;
    char ch, filename[10];
    printf (" Please enter filename :");
    scanf ("%s", filename);
    if ((fp = fopen (filename, "w")) == NULL) {
    
        printf (" Unable to open \n");
        exit (0);
        }
     ch = getchar();
     printf (" Please enter the content , With # End of no. :");
     ch = getchar();
     while (ch != '#') {
    
        fputc (ch, fp);
        putchar (ch);
        ch = getchar ();
        }
      fclose (fp);
      putchar (10);
      return 0;
      }
      
[[email protected] c]# gcc -o fputc fputc.c
[[email protected] c]# ./fputc
 Please enter filename :one
 Please enter the content , With # End of no. :happy every days!#
happy every days!
[[email protected] c]# cat one
happy every days!

 Insert picture description here

版权声明
本文为[Chshyz]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230547413873.html