CLanguage file input and output functions
1, Fgetc & fputc Function
The fgetc () function is included in the stdio. h header FILE in C language. The function prototype is int fgetc (FILE * fp );
Function: read characters from the stream, that is, get the next character from the file specified by fp. Note that fp will automatically move one byte down every time one character is obtained. In this way, programmers no longer need to control fp. This function is embodied in many read/write functions.
Return Value: returns the expected character. If an error is returned, EOF is returned.
The fputc () function writes a specified character to the file stream.
Header file
# Include <stdio. h>
Define functions
Int fputc (int c, FILE * stream );
Function Description
Fputc converts parameter c to unsigned char and writes it to the file specified by parameter stream.
Return Value
Fputc () returns the successfully written character, that is, the parameter c. If EOF is returned, the write operation fails.
The following is a specific example:
# Include <stdio. h>
# Include <stdlib. h>
Int main (int argc, char * argv [])
{
FILE * fp;
Char ch;
If (fp = fopen ("test.txt", "r") = NULL)
{
Printf ("Cannot open file. \ n ");
Exit (1 );
}
While (ch = fgetc (fp ))! = EOF)
{
Fputc (ch, stdout );
}
Fclose (fp );
Return 0;
}
Routine description:
(1) The first program first opens a file named test.txt in the reader format (the file content is This is a test ).
(2) Get the file content. Every time one character is read here, the pointer fp will automatically move one byte to the back until the end of the file, that is, the EOF sign, is read, and the loop stops. Because the return value of the fgetc function is the expected character, a character type variable ch is used to accept the characters to be read.
(3) The final running result is to print the This is a test string on the screen. Of course, stdout can be replaced with a file, so that the output is written to the file.
2, Fgets & fputs Function
The basic usage of the fgets () function is: fgets (char * s, int size, FILE * stream );
Note:
1. The first parameter is the name of the array to be assigned. Note: you do not need to write square brackets behind the array name and the length of the array.
2. The second parameter is the length of the string to be read. Note that the length value here is "the actual length of the string + 1", because there is '/0' at the end of the string '.
3. The last parameter is the input device or variable. In general, we all input from the keyboard, that is, stdin. (Read from the file is not described here)
Fputs (str, fp) usage:
(1) input all text before zero terminator in str to the file.
(2) After the input is complete, no additional special characters are added, such as line breaks. If you want to wrap a line after entering str, you should call fputc ('\ n', fp) after the preceding call.
For example, the following code is used to enter a string and calculate the number of words in the string.
# Include <stdio. h>
Int main ()
{
Char ch [80];
Char t, m;
Int I = 0, count = 0, flag = 0;
Fgets (ch, 80, stdin );
Fputs (ch, stdout );
For (I = 0; ch [I]! = '\ 0'; I ++)
{If (ch [I] = '') flag = 0;
Else if (flag = 0)
{Flag = 1; count ++ ;}
}
Printf ("% d \ n", count );
Return 0;
}
The working principle of this Code is to use a flag variable for identification and a variable count for counting the number of words. Then read each character in the string one by one. When a letter is encountered, the flag value is 1, and when a space is encountered, the flag value is 0. If you encounter a letter with a flag value of 0 (indicating that the character before the letter is a space), add 1 to count until the flag is assigned a value of 0 again. When using fgets (), note that the length of the string specified by the second parameter must be equal to the length of the string. Otherwise, an overflow error occurs during program running. When the length of the input string exceeds the limit (80 in this example), the string with the limit length will be discarded.
Supplement: the behavior of fgets (buf, size, fp) is as follows:
(1) returns a line break or end EOF.
(2) read by row.
(3) The newline character '\ n' at the end of each line is also counted as the character of this line.
(4) For a buf with a size value, only size-1 characters can be read at most.
(5) automatically fills the last byte of the buf character (usually a line break) with the zero terminator ('\ 0 '). Therefore, if you want to remove the linefeed from the buf, you can: buf [strlen (buf)-1] = '\ 0'; the current premise is that the buf is large enough, it can hold a complete line (including the last line break ).
3, Fread & fwrite Functions
Fread reads data from the file stream
Header file # include <stdio. h>
Define the size_t fread function (void * ptr, size_t size, size_t nmemb, FILE * stream );
Function Description fread () is used to read data from a file stream. The stream parameter is an opened file pointer. the ptr parameter points to the data space to be read. The number of characters read is determined by the size * nmemb parameter. Fread () returns the number of nmemb actually read. If this value is smaller than the nmemb parameter, it indicates that the file may be read at the end or an error occurs. In this case, feof () must be used () or ferror () to determine what happens.
The Return Value Returns the number of nmemb actually read.
Example
# Include <stdio. h>
# Define nmemb 3
Struct test
{
Char name [20];
Int size;
} S [nmemb];
Int main (int argc, char * argv [])
{
FILE * stream;
Int I;
Stream = fopen ("/tmp/fwrite", "r ");
Fread (s, sizeof (struct test), nmemb, stream );
Fclose (stream );
For (I = 0; I <nmemb; I ++)
Printf ("name [% d] = %-20 s: size [% d] = % d/n", I, s [I]. name, I, s [I]. size );
}
Run
Name [0] = Linux! Size [0] = 6
Name [1] = FreeBSD! Size [1] = 8
Name [2] = Windows2000 size [2] = 11
Fwrite writes data to a file stream
Header file # include <stdio. h>
Define the function size_t fwrite (const void * ptr, size_t size, size_t nmemb, FILE * stream );
Function Description: fwrite () is used to write data to a file stream. The stream parameter is an opened file pointer. the ptr parameter points to the data address to be written. The total number of characters written is determined by the parameter size * nmemb. Fwrite () returns the number of nmemb actually written.
The Return Value Returns the number of nmemb actually written.
Example
# Include <stdio. h>
# Define set_s (x, y) {strcoy (s [x]. name, y); s [x]. size = strlen (y );}
# Define nmemb 3
Struct test
{
Char name [20];
Int size;
} S [nmemb];
Main ()
{
FILE * stream;
Set_s (0, "Linux !");
Set_s (1, "FreeBSD !");
Set_s (2, "Windows2000 .");
Stream = fopen ("/tmp/fwrite", "w ");
Fwrite (s, sizeof (struct test), nmemb, stream );
Fclose (stream );
}
Run
Name [0] = Linux! Size [0] = 6
Name [1] = FreeBSD! Size [1] = 8
Name [2] = Windows2000 size [2] = 11