C语言——IO操作(一)

C语言——IO操作(一)

1 标准IO介绍

I/O: stdio sysio (优先使用标准IO)

IO是一切程序实现的基础。

  • stdio

fopen(); fclose(); fgetc(); fputc(); fgets(); fputs(); fread(); fwrite();

scanf(); printf();

fseek(); ftell(); rewind();

fflush();

1.1 fopen() 和 fclose()

  • fopen();
FILE *fopen(const char *path, const char *mode);

Upon successful completion. return a FILE pointer. Otherwise, NULL is returned  and errno is set to indicate the error.
 -----------------------------------    
|	/usr/include/asm-generic/       |
|    	error-basse.h	errno.h     |
 -----------------------------------    
r	Open text file for reading. The stream is positioned at the beginning of
    the file.
    
r+	Open for reading and writing. The stream is positioned at the beginning
    of the file.
    
w	Truncate file to zero length or create text file for writing. The stream 
    is positioned at the beginning of the file.
    
w+  Open for reading and writing.  The file is created if it does not exist,
	otherwise it is truncated. The stream is positioned at the beginning of 
    the file.
   
a   Open for appending (writing at end of file). The file is created if it 
    does not exist. The stream is positioned at the end of the file.
    
a+  Open for reading and appending (writing at end of file). The file is
    created if it does not exist. The initial file position for reading is 
    at the beginning of the file, but output is always appended to the end 
    of the file.
  • perror() 打印错误原因。
	void perror(const char *s);

	#include 

	const char *sys_errlist[];
	int sys_nerr;
	int errno;

示例
=======================================================================
#include 
#include 
#include 

int main(){

    FILE *fp;

    fp = fopen("tmp", "r");

    if(fp == NULL){
        // fprintf(stderr, "fopen fail!\nerrno = %d\n", errno);
        perror("fopen()");
        exit(-1);
    }

    puts("OK");
    return 0;
}

结果:
-----------------------------------------------------------------------
fopen(): No such file or directory
  • strerror()
	#include 
	
	char *strerror(int ernum);
示例
========================================================================
#include 
#include 
#include 
#include 
int main(){

    FILE *fp;

    fp = fopen("tmp", "r");

    if(fp == NULL){
        
        fprintf(stderr, "fopen():%s\n", strerror(errno));        
        exit(-1);
    }

    puts("OK");
    return 0;
}

结果
-----------------------------------------------------------------------
fopen():No such file or directory
  • fclose();
	int fclose(FILE *stream);

	The fclose() function flushes the stream pointed to by stream (writing 
    any buffered output data using fflush(3)) and closes the underlying file 
    descriptor.

	The behaviour of fclose() is undefined if the stream parameter is an 
    illegal  pointer, or is a descriptor already passed to a previous 
    invocation of fclose().
        
    Upon successful completion, 0 is returned.  Otherwise, EOF is returned 
    and errno is set to indicate the error. In either case, any further 
    access (including another call to fclose()) to the  stream  results in  
    undefined behavior.

打开的文件流一定要关闭!!!

1.2 fgetc() 和 fputc()

  • fgetc();
	getc 被定义成宏;
	fgetc 被定义成函数;
    从标准输入流/成功打开的文件流中读入
        成功返回 int	失败返回 EOF
  • fputc();
	同上;
  • 简单的copy函数
#include 
#include 
#include 
#include 

int main(int argc, char *argv[]){

    FILE *fps, *fpd;
    int ch = EOF;

    if (argc < 3){
        fprintf(stderr, "Usage:%s  \n", argv[0]);
        exit(-1);
    }

    fps = fopen(argv[1], "r");
    if (fps == NULL){
        perror("fopen()");
        exit(-1);
    }

    fpd = fopen(argv[2], "w");
    if (fpd == NULL){
        fclose(fps);
        perror("fopen()");
        exit(-1);
    }

    while (1){
        ch = fgetc(fps);
        if (ch == EOF){
            break;
        }
        fputc(ch, fpd);
    }

    fclose(fps);
    fclose(fpd);

    return 0;
}

使用演示:
--------------------------------------------------------------------
./mycopy /etc/services /tmp/out    
  • 文件字符统计
#include 
#include 
#include 
#include 


int main (int argc, char *argv[]){

    FILE *fp;
    int count = 0;
    if (argc < 2){
        fprintf(stderr, "Usage:%s \n", argv[0]);
        exit(-1);
    }

    fp = fopen(argv[1], "r");
    if (fp == NULL){
        perror("fopen()");
        exit(-1);
    }

    while (fgetc(fp) != EOF){
        count++;
    }
    printf("count = %d\n", count);
    fclose(fp);


    return 0;
}


使用演示:
----------------------------------------------------------------------
./fgetc mycopy.c

结果:
------------------------
count = 714

1.3 fgets() 和 fputs()

  • fgets()
	gets()函数不安全,不检查缓冲区是否溢出,不要使用gets()。可以用fgets()代替。
    
	char *fgets(char *s, int size, FILE *stream);

	reads in at most one less than size characters from stream and stores 
    them into the buffer pointed to by s. Reading stops after an EOF or a 
    newline. If a newline is read, it is stored into the buffer. A termi‐
    nating null byte ('\0') is stored after the last character in the buffer.

    fgets(buf, SIZE, stream);  //文件末尾有一个换行符 '\n'
	1.读入一个SIZE-1长度的字符串
    	最后一个字符为'\0' 有效字符为SIZE-12.读入字符串长度小于SIZE
        最后为'\n''\0'
  • fputs()
	char *fputs(const char *s, FILE *stream);
  • copy改进
#include 
#include 
#include 
#include 

#define BUF_SIZE    1024

int main(int argc, char *argv[]){

    FILE *fps, *fpd;
    char buf[BUF_SIZE];

    if (argc < 3){
        fprintf(stderr, "Usage:%s  \n", argv[0]);
        exit(-1);
    }

    fps = fopen(argv[1], "r");
    if (fps == NULL){
        perror("fopen()");
        exit(-1);
    }

    fpd = fopen(argv[2], "w");
    if (fpd == NULL){
        fclose(fps);
        perror("fopen()");
        exit(-1);
    }

    while (fgets(buf, BUF_SIZE, fps) != NULL){
        
        fputs(buf, fpd);
    }

    fclose(fps);
    fclose(fpd);

    return 0;
}

1.4 fread() 和 fwrite()

  • fread()
	size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
	size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

	PTR_SIZE == size * nmemb;

	On success, fread() and fwrite() return the number of items read or 
    written. This number equals the number of bytes transferred only when 
    size is 1. If an error occurs, or the end of the  file  is  reached, 
	the return value is a short item count (or zero).
        
    返回值为成功读取对象的数量,成功至少为1个对象,不足一个对象失败返回0
  • copy改进
    while ((n = fread(buf, 1, BUF_SIZE, fps)) > 0){
		fwrite(buf, 1, n, fpd);
    }

你可能感兴趣的:(C语言,c语言)