C的文件IO函数

经常遇到在看各种书籍的时候对io类的各种描述在这里希望总结一下,留到下次进行阅读

file* f;

fclose(f); 关闭文件流f

fopen(fname, mode) / fopen_s(fname , mode, file*) // 开启一个文件流

 
FILE *freopen( 
   const char *path,
   const char *mode,
   FILE *stream 
);
FILE *_wfreopen( 
   const wchar_t *path,
   const wchar_t *mode,
   FILE *stream 
);    //函数,以指定模式重新指定到另一个文件。模式用于指定新文件的访问方式。



int main()// ungetc()函数的使用
{
    int ch;
    int result = 0;

    // Read in and convert number:
    while( ((ch = getchar()) != EOF) && isdigit( ch ) )
        result = result * 10 + ch - '0';    // Use digit.
    if( ch != EOF )
        ungetc( ch, stdin );                // 将读取的字符返回不是数字的位置(ch)
    printf( "Number = %d\nNext character in stream = '%c'",
        result, getchar() );

    system("pause");
    return 0;
}



int main()     //efof() fopne()  fclose() fwrite();
{
    int  count, total = 0;
    char buffer[100];
    FILE *stream = NULL;
    FILE *InFile = NULL;
    fopen_s(&InFile, "a.txt", "a+");
    if (InFile == NULL)
    {
        exit(-1);
    }
    fopen_s( &stream,__FILE__, "r" );
    if( stream == NULL )
        exit( 1 );

    // Cycle until end of file reached:
    while( !feof( stream ) ) // if is the end file return nonzero value
    {
        // Attempt to read in 100 bytes:
        memset(buffer, 0 , sizeof(buffer));
        count = fread( buffer, sizeof( char ), 100, stream );
        if( ferror( stream ) )      {
            perror( "Read error" );
            break;
        }
        fwrite(buffer, sizeof(char), count, InFile);
        // Total up actual bytes read
        total += count;
    }
    printf( "Number of bytes read = %d\n", total );
    fputc('\n', InFile);
    fclose( stream );
    fclose(InFile);
    system("pause");
    return 0;
}



clearerr的作用是使文件错误标志和文件结束标志置为0.假设在调用一个输入输出函数时出现了错误,ferror函数值为一个非零值。在调用clearerr(fp)后,ferror(fp)的值变为0。
只要出现错误标志,就一直保留,直到对同一文件调用clearerr函数或rewind函数,或任何一个输入输出函数。



rewind函数作用等同于 (void)fseek(stream, 0L, SEEK_SET);

int main()  //以文本文件的形式读写文件
{
    FILE   *Instream, *OutStream;

    char   buffer[256];

    if( fopen_s( &Instream, __FILE__, "r" ) || fopen_s(&OutStream, "b.txt", "w"))
    {
        perror( "Trouble opening file" );
        return -1;
    }

    while (!feof(Instream))
    {
        fgets(buffer, 256, Instream);
        if (buffer[0] != '\0')
        {
            fputc('>', OutStream);
        }
        fputs(buffer, OutStream);

    }

    fclose(Instream);
    fclose(OutStream);

    system("pause");
    return 0;
}





发布了25 篇原创文章 · 获赞 5 · 访问量 3230

猜你喜欢

转载自blog.csdn.net/Ellis1993/article/details/77986410