1. Read-write character function putc () and getc ()
These two functions are similar to the Putchar () and the GetChar () functions. Assuming FP is a file pointer, ch is a character variable,
ch = getc(fp);// ch = getchar();
putc(ch,fp);// putchar(ch);
C implementation that outputs the contents of a file (by character) to the standard output:
#include <stdio.h>
#include <stdlib.h>
/* 将文件内容(按字符)输出到标准输出 */
void read_ch(char * filename, char * mode)
{
int ch;
FILE * fp;
if ((fp = fopen(filename,mode)) == NULL)
{
fprintf(stderr,"Can't open %s.\n",filename);
exit(1);
}
while ((ch = getc(fp)) != EOF)
putc(ch,stdout);
fclose(fp);
}
2. Read-Write line function fgets () and fputs ()
The gets () function requires only one parameter (char *), while the fgets () function requires three parameters (char *, int, FILE *). The first parameter is the address used to store the input, the second parameter represents the maximum length of the string, and the last parameter is the file pointer. are usually:
Fgets (buf, MAX, FP);//gets (BUF);
The fgets () function reads after the first newline character it encounters, or reads less than one character from the maximum length of the string, or reads to EOF. Then it adds a ' ' to the end ', which makes up a string. (This is different from the gets (), it reads "\ n" and adds a ', ' and when read again, it discards ' \ n '). Similar to gets (), fgets () returns NULL when it encounters EOF, otherwise it returns the address passed to it.
The fputs () function accepts two parameters, (char *, FILE *). Unlike puts (), it does not automatically add ' \ n '. are usually:
Fputs (BUF, FP);//puts (BUF);
C implementation that outputs the contents of a file (by rows) to standard output:
#include <stdio.h>
#include <stdlib.h>
#define MAXLINE 21
/* 将文件内容(按行)输出到标准输出 */
void read_line(char * filename, char * mode)
{
char line[MAXLINE];
FILE * fp;
if ((fp = fopen(filename,mode)) == NULL)
{
fprintf(stderr,"Can't open %s.\n",filename);
exit(1);
}
while (fgets(line, MAXLINE,fp) != NULL)
fputs(line,stdout);
fclose(fp);
}