I/O函数

来源:互联网 发布:云计算ppt模板百度云 编辑:程序博客网 时间:2024/05/20 02:56

  本篇博客将简单介绍一些普遍使用的IO函数,如fflush、ftell、fgetpos、feof、remove等。
以下便是要介绍的函数:

1.fflush(file flush):

  此函数包含在stdio.h头文件中,用来强制将缓冲区中的内容写入文件。
函数原型:int fflush(FILE *stream) ;
函数功能:清除一个流,即清除文件缓冲区,当文件以写方式打开时,将缓冲区内容写入文件。也就是 说,对于ANSI C规定的是缓冲文件系统,函数fflush用于将缓冲区的内容输出到文件中去。
函数返回值:A zero value indicates success.
      If an error occurs, EOF is returned and the error indicator is set (see ferror).
如果成功刷新,fflush返回0。指定的流没有缓冲区或者只读打开时也返回0值。若出现错误返回EOF。
函数用法:fflush(stdin)刷新标准输入缓冲区,把输入缓冲区里的东西清除
     fflush(stdout)刷新标准输出缓冲区,把输出缓冲区里的东西打印到标准输出设备上。

#include <stdio.h>char mybuffer[80];int main(){    FILE * fp;    fp = fopen("myfile.txt", "r+");    if (fp == NULL)    {        perror("Error opening file");    }    else     {        fputs("test", fp);   //向指定流中写入字符串        fflush(fp);    // 刷新或重新定位要求        fgets(mybuffer, 80, fp);   //从流中读取字符串        puts(mybuffer);     //将读出的字符串格式化输出    }    fclose(fp);    return 0;}

结果如下:
结果

2.ftell:

  此函数包含在stdio.h头文件中,用来返回回当前文件指针的位置
函数原型:long int ftell ( FILE * stream );
函数功能:返回当前文件指针的位置。这个位置是指当前文件指针相对于文件开头的位移量。
函数返回值:On success, the current value of the position indicator is returned.
      On failure, -1L is returned, and errno is set to a system-specific positive value.
若成功,则返回文件指针的位置;若出错,则返回–1L。
函数用法:该函数对大于2³¹-1文件,即:2.1G以上的文件操作时可能出错。

#include <stdio.h>int main(){    FILE *fp;    long size;    fp = fopen("myfile.txt", "rb");    if (fp == NULL)    {        perror("Error opening file");        exit(1);    }    else    {        fseek(fp, 0, SEEK_END);   //对操作位数进行重新设置,设置在结束位置且偏移量为0        size = ftell(fp);     //得到文件位置指针相对于文件首的偏移字节数        fclose(fp);        printf("Size of myfile.txt: %ld bytes.\n", size);    }    return 0;}

结果如下:
结果

3.fseek:

此函数包含在stdio.h头文件中,用来重定位流(数据流/文件)上的文件内部位置指针
函数原型:int fseek ( FILE * stream, long int offset, int origin );
     stream:指向流的指针
     offset:指针偏移量
     origin:基准
     SEEK_SET:设置到开始位置
     SEEK_CUR:设置到当前位置
     SEEK_END:设置到结束位置
函数功能:如果执行成功,stream将指向以origin为基准,偏移offset(指针偏移量)个字节的位置。如果执行失败(比如offset超过文件自身大小),则不改变stream指向的位置。
函数返回值:If successful, the function returns zero.
      Otherwise, it returns non-zero value.
      If a read or write error occurs, the error indicator (ferror) is set.
如果执行成功,函数返回0。如果执行失败,函数返回一个非0值。如果是一个读写错误,ferror函数执行报错。
函数用法:

#include <stdio.h>int main(){    FILE *fp;    long size;    fp = fopen("myfile.txt", "rb");    if (fp == NULL)    {        perror("Error opening file");        exit(1);    }    else    {        fseek(fp, 0, SEEK_END);   //对操作位数进行重新设置,设置在结束位置且偏移量为0        size = ftell(fp);     //得到文件位置指针相对于文件首的偏移字节数        fclose(fp);        printf("Size of myfile.txt: %ld bytes.\n", size);    }    return 0;}

结果如下:
结果

4.setbuf:

此函数包含在stdio.h头文件中,主要用于打开和关闭缓冲机制。
函数原型:void setbuf ( FILE * stream, char * buffer );
     stream:指向流的指针
     buffer:期望缓冲区的地址
函数功能:把缓冲区与流相联
函数返回值:无返回值
函数用法:setbuf函数具有打开和关闭缓冲机制。为了带缓冲进行I/O,参数buffer必须指向一个长度为BUFSIZ(定义在stdio.h头文件中)的缓冲区。通常在此之后该流就是全缓冲的,但是如果该流与一个终端设备相关,那么某些系统也可以将其设置为行缓冲。为了关闭缓冲,可以将buffer参数设置为NULL。

#include <stdio.h>int main(){    char buffer[BUFSIZ];    //指向一个长度为BUFSIZ(定义在stdio.h头文件中)的缓冲区    FILE *fp1, *fp2;    fp1 = fopen("myfile1.txt", "w");    fp2 = fopen("myfile2.txt", "a");    setbuf(fp1, buffer);    fputs("This is sent to a buffered stream", fp1);    fflush(fp1);    setbuf(fp2, NULL);    fputs("This is sent to an unbuffered stream",fp2);    fclose(fp1);    fclose(fp2);    return 0;}

结果如下:
结果

5.setvbuf:

函数原型:int setvbuf ( FILE * stream, char * buffer, int mode, size_t size );
     stream:指向流的指针
     buffer:期望缓冲区的地址
     mode:期望缓冲区的类型:
       _IOFBF(满缓冲):当缓冲区为空时,从流读入数据。或者当缓冲区满时,向流写入数据。
       _IOLBF(行缓冲):每次从流中读入一行数据或向流中写入一行数据。
       _IONBF(无缓冲):直接从流中读入数据或直接向流中写入数据,而没有缓冲区。
size:缓冲区内字节的数量。
函数功能:把缓冲区与流相关
函数返回值:If the buffer is correctly assigned to the file, a zero value is returned.
     Otherwise, a non-zero value is returned; This may be due to an invalid mode parameter or to some other error allocating or assigning the buffer.
  如果该缓冲区被正确地分配给该文件,则返回零值。否则,返回非零值;这可能是由于一个无效的模式参数或其他错误或分配缓冲区的错误。
函数用法:

#include <stdio.h>int main(){    FILE *pFile;    pFile = fopen("myfile.txt", "w");    setvbuf(pFile, NULL, _IOFBF, 1024);  //文件操作,当缓冲区为空时,从流读入数据。或者当缓冲区满时,向流写入数据。    fclose(pFile);    return 0;}

结果如下:
结果

6.rewind:

此函数包含在stdio.h头文件中,用于将文件内部的指针重新指向一个流的开头。
函数原型:void rewind ( FILE * stream );
函数功能:将文件内部的位置指针重新指向一个流(数据流/文件)的开头
函数返回值:无返回值
函数用法:

#include <stdio.h>int main(){    char str[80];    float f;    FILE *fp;    fp = fopen("myfile.txt", "w+");    fprintf(fp, "%f %s", 3.14, "PI");    rewind(fp);     //重新指向流的开头    fscanf(fp, "%f", &f);   //从流中读出3.14    fscanf(fp, "%s", str);   //从流中读出字符串"PI"    fclose(fp);    printf("I have read:%f and %s\n", f, str);   //将读出的数据格式化输出    return 0;}

结果如下:
结果

结果

7.fgetpos:

此函数包含在stdio.h头文件中,用来获取当前访问指针位置信息
函数原型:int fgetpos ( FILE * stream, fpos_t * pos );
     pos:是指向 fpos_t * 类型的一个指针。
     stream:指向流的指针
函数功能:取得当前文件的指针所指的位置,并把该指针所指的位置数存放到pos所指的对象中。
函数返回值:On success, the function returns zero.
     In case of error, errno is set to a platform-specific positive value and the function returns a non-zero value.
如果成功,函数返回0;否则返回一个非零值并设置errno。
函数用法:

#include <stdio.h>int main(){    FILE * fp;    int c;    int n;    fpos_t pos;    fp = fopen("myfile.txt", "r");    if (fp == NULL)    {        perror("Error opening file");    }    else    {        c = fgetc(fp);        printf("1st character is %c\n", c);        fgetpos(fp, &pos);   //取得当前文件的指针所指的位置        for (n = 0; n<3; n++)        {            fsetpos(fp, &pos);   //将文件指针定位在pos指定的位置上            c = fgetc(fp);            printf("2nd character is %c\n", c);        }        fclose(fp);    }    return 0;}

结果如下:

结果

8.fsetpos:

此函数包含在stdio.h头文件中,用来定位流上的文件指针
函数原型:int fsetpos ( FILE * stream, const fpos_t * pos );
     pos:是指向 fpos_t * 类型的一个指针
     stream:指向流的指针
函数功能:将文件指针定位在pos指定的位置上。该函数的功能与前面提到的fgetpos相反,是将文件指针fp按照pos指定的位置在文件中定位。pos值以内部格式存储,仅由fgetpos和fsetpos使用。
函数返回值:If successful, the function returns zero.
     On failure, a non-zero value is returned and errno is set to a system-specific positive value.
如果成功,返回0,否则返回一个非零值,并设置全局变量errno为正值,这可以解释同perrno。
函数用法:

#include <stdio.h>int main(){    FILE * fp;    int c;    int n;    fpos_t pos;    fp = fopen("myfile.txt", "r");    if (fp == NULL)    {        perror("Error opening file");    }    else    {        c = fgetc(fp);        printf("1st character is %c\n", c);        fgetpos(fp, &pos);   //取得当前文件的指针所指的位置        for (n = 0; n<3; n++)        {            fsetpos(fp, &pos);   //将文件指针定位在pos指定的位置上            c = fgetc(fp);            printf("2nd character is %c\n", c);        }        fclose(fp);    }    return 0;}

结果如下:
结果

9.feof(file-end-of-file):

此函数包含在stdio.h头文件中,用来检测流上的文件结束符
函数原型:int feof ( FILE * stream );
函数功能:检测流上的文件结束符(二进制中可能会出现-1(EOF),所以判结束只能用feof)
函数返回值:A non-zero value is returned in the case that the end-of-file indicator associated with the stream is set.
     Otherwise, zero is returned.
如果文件结束,则返回非0值,否则返回0。
函数用法:

#include <stdio.h>int main(){    FILE * fp;    int n = 0;    fp = fopen("myfile.txt", "rb");    if (fp == NULL)    {        perror("Error opening file");    }    else    {        while (fgetc(fp) != EOF)         {            ++n;        }        if (feof(fp))         {            puts("End-of-File reached.");   //找到文件结束处            printf("Total number of bytes read: %d\n", n);   //输出读取的字节总数        }        else        {            puts("End-of-File was not reached.");        }    }    fclose(fp);    return 0;}

结果如下:
结果

10.ferror:

此函数包含在stdio.h头文件中,用来判断是否出错
函数原型:int ferror ( FILE * stream );
函数功能:判断是否出错
函数返回值:A non-zero value is returned in the case that the error indicator associated with the stream is set.
      Otherwise, zero is returned.
如果ferror返回值为0(假),表示未出错。如果返回一个非零值,表示出错。
函数用法:

#include <stdio.h>int main(){    FILE * fp;    fp = fopen("myfile.txt", "r");    if (fp == NULL)    {        perror("Error opening file");    }    else     {        fputc('x',fp);        if (ferror(fp))        {            printf("Error Writing to myfile.txt\n");     //在只读模式下的txt,尝试将一个字符写入,报错        }    }    fclose(fp);    return 0;}

结果如下:
结果

11.clearerr:

此函数包含在stdio.h头文件中,用来清除结束文件和错误指标给定的流。
函数原型:void clearerr ( FILE * stream );
函数功能:复位错误标志
函数返回值:无返回值
函数用法:

#include <stdio.h>int main(){    FILE * fp;    fp = fopen("myfile.txt", "r");    if (fp == NULL)    {        perror("Error opening file");    }    else     {        fputc('x', fp);        if (ferror(fp))         {            printf("Error Writing to myfile.txt\n");      //在只读模式下的txt,尝试将一个字符写入,报错            clearerr(fp);      //清除结束文件和错误指标给定的流        }        fgetc(fp);        if (!ferror(fp))           {            printf("No errors reading myfile.txt\n");        }    }    fclose(fp);    return 0;}

结果如下:
结果

12.tmpfile:

函数原型:FILE * tmpfile ( void );
函数功能:以wb+形式创建一个临时二进制文件
函数返回值:If successful, the function returns a stream pointer to the temporary file created.
      On failure, NULL is returned.
如果成功,该函数返回一个流指针创建的临时文件。如果不能创建文件,则返回NULL。
函数用法:

#include <stdio.h>#include <string.h>int main(){    char buffer[256];    FILE * fp;    fp = tmpfile();    //创建一个临时文件来存储用户输入的行    do {        if (!fgets(buffer, 256, stdin))        {            break;        }        fputs(buffer, fp);    } while (strlen(buffer)>1);    rewind(fp);    //重新指向流的开头    while (!feof(fp))    {        if (fgets(buffer, 256, fp) == NULL)     //当用户输入空行时,程序将对临时文件进行重新调整,并将其内容打印到stdout        {            break;        }        fputs(buffer, stdout);    }    fclose(fp);    return 0;}

结果如下:
结果

13.remove:

函数原型:int remove(char*filename);
  filename为要删除的文件名,可以为一目录。如果参数filename 为一文件,则调用unlink()处理;若参数filename 为一目录,则调用rmdir()来处理。
函数功能:删除数组、链表对象所有的元素
函数返回值:成功则返回0,失败则返回-1,错误原因存于errno。
函数用法:

#include <stdio.h>int main(){    int result;    char newname[] = "newname.txt";    result = remove(newname);    //删除newname文件    if (result == 0)    {        puts("File successfully removed");    }    else    {        perror("Error removing file");    }    return 0;}

结果如下:
当newname文件不存在时:

结果

当newname文件存在时:

结果

结果

14.rename:

此函数包含在stdio.h头文件中,用来给一个文件重命名
函数原型:int rename ( const char * oldname, const char * newname );
oldname:旧文件名
newname:新文件名
函数功能:用该函数可以实现文件移动功能,把一个文件的完整路径的盘符改一下就实现了这个文件的移动。
函数返回值:if the file is successfully renamed, a zero value is returned.
      On failure, a nonzero value is returned.
      On most library implementations, the errno variable is also set to a system-specific error code on failure.
执行成功则返回0,失败返回非0,错误原因存于errno
函数用法:

#include <stdio.h>int main(){    int result;    char oldname[] = "oldname.txt";    char newname[] = "newname.txt";    result = rename(oldname, newname);    //将文件oldname重命名为newname    if (result == 0)    {        puts("File successfully renamed");    }    else    {        perror("Error renaming file");    }    return 0;}

结果如下:
当oldname文件不存在时:
结果1

当oldname文件存在时:

结果

结果2

原创粉丝点击