C file reading and writing


In the previous chapter we explained the standard input and output devices for C language processing. In this chapter we will introduce how C programmers create, open, and close text or binary files.

A file, whether it is a text file or a binary file, represents a series of bytes. The C language not only provides top-level functions to access, but also provides low-level (OS) calls to process files on storage devices. This chapter will explain the important calls of file management.

Open a file

You can use the fopen( ) function to create a new file or open an existing file. This call will initialize the type# An object of ##FILE, type FILE contains all the necessary information to control the flow. The following is the prototype of this function call:

FILE *fopen( const char * filename, const char * mode );

Here,

filename is a string used to name the file, and the value of the access mode mode can be one of the following values One of:

ModeDescription##rwar+w+a+

If you are processing a binary file, you need to use the following access mode to replace the above access mode:

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Close the file

;

In order to close the file, please use the fclose() function . The prototype of the function is as follows:

 int fclose( FILE *fp );

If the file is successfully closed, the fclose( ) function returns zero. If an error occurs when closing the file, the function returns EOF. This function actually clears the data in the buffer, closes the file, and frees all memory used for the file. EOF is a constant defined in the header file stdio.h.

The C standard library provides various functions to read and write files character by character or as fixed-length strings.

Write to file

The following is the simplest function to write characters to the stream:

int fputc( int c, FILE *fp );

Functionfputc() Put the parameter c The character value is written to the output stream pointed to by fp. It returns the characters written if the write was successful, or EOF if an error occurred. You can use the following function to write a null-terminated string to the stream:

int fputs( const char *s, FILE *fp );

Functionfputs() Write the string s into the output stream pointed to by fp. It returns a non-negative value if the write is successful, or EOF if an error occurs. You can also use the int fprintf(FILE *fp,const char *format, ...) function to write a string to a file. Try the following example:

Note: Please make sure you have the /tmp directory available, if it does not exist, you need to create it on your computer first the directory.

#include <stdio.h>main(){
   FILE *fp;

   fp = fopen("/tmp/test.txt", "w+");
   fprintf(fp, "This is testing for fprintf...\n");
   fputs("This is testing for fputs...\n", fp);
   fclose(fp);}

When the above code is compiled and executed, it creates a new file test.txt in the /tmp directory and writes two lines using two different functions . Next let's read this file.

Read file

The following is the simplest function to read a single character from a file:

int fgetc( FILE * fp );

fgetc() The function points to from fp Read a character from the input file. The return value is the character read, or EOF if an error occurs. The following function allows you to read a string from a stream:

char *fgets( char *buf, int n, FILE *fp );

Function fgets() Reads n - 1 characters from the input stream pointed to by fp. It copies the read string into buffer buf and appends a null character at the end to terminate the string.

If this function encounters a newline character '\n' or end-of-file EOF before reading the last character, only the characters read, including the newline character, are returned. You can also use the int fscanf(FILE *fp, const char *format, ...) function to read a string from a file, but it stops when it encounters the first space character Read.

#include <stdio.h>main(){
   FILE *fp;   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);}

When the above code is compiled and executed, it reads the file created in the previous section, producing the following results:

1 : This2: is testing for fprintf...3: This is testing for fputs...

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

Binary I/O functions

The following two functions are used for binary input and output:

size_t fread(void *ptr, size_t size_of_elements, 
             size_t number_of_elements, FILE *a_file);              size_t fwrite(const void *ptr, size_t size_of_elements, 
             size_t number_of_elements, FILE *a_file);

Both functions are used to read and write storage blocks - usually Is an array or structure.

Open an existing Text file, allows the file to be read.
Open a text file, allowing writing to the file. If the file does not exist, a new file is created. Here, your program writes from the beginning of the file.
Open a text file and write to the file in append mode. If the file does not exist, a new file is created. Here, your program appends content to the existing file content.
Open a text file, allowing reading and writing of the file.
Open a text file, allowing reading and writing of the file. If the file already exists, the file is truncated to zero length, if the file does not exist, a new file is created.
Open a text file, allowing reading and writing of the file. If the file does not exist, a new file is created. Reading will start from the beginning of the file, and writing will only be in append mode.