[C language] file input and output operations

open a file

  • fopen(): create a new file/open an existing file, initialize an object of type FILE, containing all necessary information for control flow
    • FILE *fopen(const char *filename, const char *mode);
    • model:
      • r: open an existing text file, allowing reading
      • w: open a text file, allow writing ; if there is no file, create a new one; if there is, rewrite
      • a: Open a text file, write in append mode ; if there is no file, create a new one; append content
      • r+: open a text file, allowing reading and writing
      • w+: open a text file, allow reading and writing ; create a new one if there is no file; rewrite if there is one
      • a+: open a text file, allowing reading and writing ; if there is no file, create a new one; read from the beginning, write and append

close file

  • fclose():
    • int fclose(FILE *fp);
    • Close successfully returns 0
    • Close failure returns EOF

write to file

  • fputc(): Write the character value of parameter c to the output stream pointed to by fp, return the written character if successful, and return EOF if it fails
    • int fputc(int c, FILE *fp);
  • fputs(): Write the string s to the output stream pointed to by fp, returning a non-negative value if successful, or EOF if it fails
    • int fputs(const char *s, FILE *fp);
  • fprintf(): a string to write to the file
    • int fprintf(FILE *fp, const char *format, ...)
#include <stdio.h>
int main()
{
    FILE *fp = NULL;
    fp = fopen("/tmp/test.txt", "w+");
    fputs("Shenzhen", fp);
    fprintf(fp, "Tianjin");
    fclose(fp);
}

read file

  • fgetc(): Read a character from the input file pointed to by fp, return the read character, or return EOF on failure
    • int fget(FILE * fp);
  • fgets(): Read n-1 characters from the input stream pointed to by fp. If a newline character/end of file EOF is encountered on the way, return the read characters
    • char *fgets(char *buf, int n, FILE *fp);
  • fscanf(): read string from file, stop at first space/newline
    • int fscanf(FILE *fp, const char *format, ...)
#include <stdio.h>

#include <stdio.h>
 
int main()
{
   FILE *fp = NULL;
   char buff[255];
 
   fp = fopen("/tmp/test.txt", "r");
   fscanf(fp, "%s", buff);
   printf("1: %s\n", buff );
 
   fgets(buff, 255, (FILE*)fp);
   printf("2: %s\n", buff );
   
   fgets(buff, 255, (FILE*)fp);
   printf("3: %s\n", buff );
   fclose(fp);
}

First, the fscanf() method only reads This, because it encounters a space after it. Second, it calls fgets() to read the remainder until the end of the line. Finally, calls fgets() to read the second line in its entirety .

Guess you like

Origin blog.csdn.net/weixin_46143152/article/details/126683701