Chinaunix首页 | 论坛 | 博客
  • 博客访问: 128515
  • 博文数量: 62
  • 博客积分: 1476
  • 博客等级: 上尉
  • 技术积分: 662
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-03 16:38
文章分类

全部博文(62)

文章存档

2010年(14)

2009年(48)

我的朋友

分类: C/C++

2009-12-06 15:49:18

  对于一个刚入门的程序员来说,最亲切的莫过于面对一些简洁明了的样例代码,而不是一本巨厚无比,沉长冗余,解释得婆婆妈妈的某某<xx从入门到精通>之类的书了。清楚明了的sample code使我们更加亲切,于是我把我当年编程入门时写的一些代码,稍加整理,贴出来让广大刚入门的同僚们参考。我的代码前面一般都会有一些库函数说明,都是自己一字一字地敲上去,把巨厚无比的书压缩成了几句核心注意事项,因此,老鸟们要是对某个函数返回值或者使用方法有些模糊,也可以借此作为参考手册。

  下面是此系列的第一章:stdio中的文件操作指南


/*******************************************************************************
* Codified by Z
* header
* function serial:
*    FILE *fopen( const char *filename, const char *type ); return NULL(fail)
*    FILE *freopen( const char *filename, const char *type, FILE *stream );
*    int fclose( FILE *stream ); return 0(success) else EOF(fail);
*    
*    int remove( const char *filename ); rm file or directory, lnk = unlink()
*    int rename( const char *oldname, const char *newname );
*    
*    FILE *tmpfile( void ); open a unique tmp file and return fp else NULL(fail)
*    char *tmpnam( char *name ); get an unique file name, only call TMP_MAX times
*
* note:
* File open type:
* [RWA] ONLY UNIX. R: readonly, error when none exist; W: write only, if exists,
* clear file else create. A: if exists, append at tail, else create.
* [r+w+a+] r+: rw, error when none exist; w+: rw, if exists, clear file, else
* create; a+: rw and only append at tail, able to read all over file.
* [bt] b: binary; t:text.
*
* rename: newname mustn't include oldname(e.g. rename("/tmp", "/tmp/obj");)
*    1. regular file: newname mustn't be a dir in that path, else is OK.
*    2. directory: newname non-exist or newname is am empty dir.
*
* location:
*    int fseek( FILE *stream, long int offset, int whence ); return 0 else ~0
*    void rewind( FILE *stream ); rewind file to SEEK_SET
*    long int ftell( FILE *stream ); get current file pointer location
*    int fgetpos( FILE *stream, fpos_t *position ); return 0 else ~0(failed)
*    int fsetpos( FILE *stream, const fpos_t *position );
* note:
* fseek whence option:
*    SEEK_SET: begin.    ( 0 + offset )
*    SEEK_CUR: current    ( cur + offset )
*    SEEK_END: end, offset<0 ( end + offset )
*
* fgetpos: get the postion pointer to fpos_t
*
* check:
*    int ferror( FILE *stream ); return 0 or not(error)
*    int feof( FILE *stream ); when reach EOF return ~0 else 0(not end)
*    void clearerr( FILE *stream ); clear error and EOF status
*
*
* buffer:
*    void setbuf( FILE *stream, char *buf );
*    int setvbuf( FILE *stream, char *buf, int type, size_t size );
*    int fflush( FILE *stream );
* note:
* setbuf(): buf is char buf[BUFSZ]; BUFSZ is a const int defined in stdio.h.
* setvbuf(), way of buffer:
*    _IOFBF: full buffer; _IOLBF: line buffer; _IONBF: none buffer.
*    buf and size only effect when full or line buffer. return 0 else ~0.
* fflush(): force flush stream, if stream is NULL, os force flush all stream.
*
*
* File read/write:
* Function serial:
* charactor:
*    int getc( FILE *stream ); NB: return int, not char. return char or EOF
*    int getchar(void); #define getchar() getc(stdin)
*    int fgetc( FILE *stream ); much slower than getc()
*
*    int putc( int c, FILE *stream ); return c(be written) else return EOF
*    int putchar( int c ); #define putchar(c) putc(c,stdout)
*    int fputc( int c, FILE *stream ); much slower than fputc()
*    int ungetc( int c, FILE *stream ); push back c and fseek(fp, -1, SEEK_CUR)
* line:
*    char *gets( char *s ); auto add '\0' to s, return s or NULL(failed)
*    char *fgets( char *s, int n, FILE *stream ); read n-1 chars at most.
*
*    int puts( const char *s ); add '\n', return number of written char, EOF
*    int fputs( const char *s, FILE *stream ); only string s, no '\n'
* block:
*    size_t fread( void *ptr, size_t size, size_t nitems, FILE *stream );
*    size_t fwrite( const void *ptr, size_t size, size_t nitems, FILE *str );
* note:
*    1. block rw often used to store/recovry memory data structure.
*    2. return number items, not number of bytes.
*
*
* format:
*    int printf( const char *format, ... ); return number of written chars
*    int fprintf( FILE *stream, const char *format, ... );
*    int sprintf( char *s, const char *format, ... ); [arg,]
*    
*    int scanf( const char *format, ... ); return nnumber of args, not chars
*    int fscanf( FILE *stream, const char *format, ... );
*    int sscanf( const char *s, const char *format, ... ); [ptr,]
* note:
* %[tag][width][.precision]type
*    tag:[-+ #] -: left; +: right; space: +/-number; #: 0(oct)/0x[hex]
*    width/precision: set output width/precision.
*    type: [diu], [feEgG], [xX], [o], [cs], [p%]. eE: exp. gG: %f/%e. p: ptr.
*
*
* string:
* header file
*    extern int errno;
*    void perror( const char *str );
*    char *strerror( int errnum ); get error info of errnum, strerror(errno)
*    char *strstr( char *s1, char *s2 ); return start of s2 in s1, else NULL.
*    
* return 0 (success) or return -1 (failed)
*******************************************************************************/

#include <stdio.h>
#include <stdlib.h>

int main( int ac, char *av[] )
{
    printf( "Hello" );
    
    return 0;
}

int file_redirect(){
    FILE *fpin = NULL, *fpout = NULL;
    
    char sz[100];
    
    memset( sz, 0, sizeof(sz) );
    
    if ( (fpin = freopen("in.txt", "rt", stdin)) == NULL ) {
        printf( "stdin > in.txt failed.\n" );
        return 1;
    }
    
    if ( (fpout = freopen("out.txt", "wt", stdout)) == NULL ) {
        printf( "stdout > out.txt failed.\n" );
        return 1;
    }
    
    while ( feof(fpin) != _IOEOF )     /* stdio/stdout is _IOEOF, file is EOF*/
        puts( gets(sz) );     /* one more line('\n', added by puts) */
    
/*    while ( gets(sz) != NULL )     // if there's an empty line, gets(sz) is NULL
        puts(sz);
*/
    
    fclose(fpin);
    fclose(fpout);

    if ( freopen( "CON", "rt", stdin ) == NULL ) {
        perror( "Recover stdin failed!\n" );
        return 1;
    }
    
    if ( freopen( "CON", "wt", stdout ) == NULL ) {
        perror( "Recover stdout failed!\n" );
        return 1;
    }
        
    return 0;
}

int file_text(){
    FILE *fpin = NULL, *fpout = NULL;
    char sz[100];
    
    memset( sz, 0, sizeof(sz) );
    
    if ( (fpin = fopen( "in.txt", "rt" )) == NULL ) {
        perror( "Failed to open file to read!\n" );
        return 1;
    }
    
    if ( (fpout = fopen( "out.txt", "wt" )) == NULL ) {
        perror( "Failed to open file to write!\n" );
        return 1;
    }
    
    while ( !feof( fpin ) ) {
        *sz = '\0';    // must be clean, or it may repeat the last line

        fgets( sz, sizeof(sz), fpin );
        fputs( sz, fpout );
    
}
    
    fclose(fpin);
    fclose(fpout);
    
    return 0;
}

int file_binary(){
    FILE *fpin = NULL, *fpout = NULL;
    int m = 0x12345678;
    
    if ( (fpin = fopen( "in.txt", "rb" )) == NULL ) {
        perror( "Failed to open file to read!\n" );
        return 1;
    }
    
    if ( (fpout = fopen( "out.txt", "wb" )) == NULL ) {
        perror( "Failed to open file to write!\n" );
        return 1;
    }
    
    fwrite( &m, sizeof(m), 1, fpout );
    
/*    while ( !feof(fpin) ) { // check if reach EOF
        //printf( "current: %ld\n", ftell(fpin) );
        c = fgetc(fpin);
        if ( feof(fpin) ) break;
        fputc( c, fpout );
    }
    
    fseek( fpin, 0, SEEK_SET );
    printf( "First: %d\n", fgetc(fpin) );
    fseek( fpin, 0, SEEK_END );
    printf( "feof: %d\n", feof(fpin) );
    printf( "Last: %d\n", fgetc(fpin) );
    printf( "feof: %d\n", feof(fpin) );
*/
    
    fclose(fpin);
    fclose(fpout);
    
    return 0;
}


阅读(721) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~