zoukankan      html  css  js  c++  java
  • 二进制文件读取写入(一)

    最近在老师推荐下,跟着田纳西大学James S. Plank的课程安排学习Unix Systems Programming

    Lab链接在这里:
    http://web.eecs.utk.edu/~plank/plank/classes/cs360/360/labs/lab2/index.html

    在这里向和我一样没接触太多程序设计同学介绍一下学习过程:

    为什么使用二进制IO

    引自:Advanced Programming in the UNIX Environment 3rd Edition

    5.9 二进制I/O
    The functions from Section 5.6 operated with one character at a time, and the functions from Section 5.7 operated with one line at a time. If we’re doing binary I/O, we often would like to read or write an entire structure at a time. To do this using getc or putc, we have to loop through the entire structure, one byte at a time, reading or writing each byte. We can’t use the line-at-a-time functions, since fputs stops writing when it hits a null byte, and there might be null bytes within the structure. Similarly, fgets won’t work correctly on input if any of the data bytes are nulls or newlines. Therefore, the following two functions are provided for binary I/O.

    函数原型

    #include <stdio.h>
    size_t fread(void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp);
    size_t fwrite(const void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp);
    Both return: number of objects read or written
    

    使用说明

    unsigned char *str_buf;
    str_buf=(char *)malloc(sizeof(char));
    *str_buf='a';
    fwrite(str_buf,sizeof(char),5,fp);
    

    运行结果

    unsigned char *str_buf;
    str_buf=(unsigned char *)malloc(sizeof(unsigned char));
    *str_buf='a';
    int i;
    for(i=0;i<5;i++)
       fwrite(str_buf,sizeof(unsigned char),1,fp);
    

    运行结果

  • 相关阅读:
    PAT乙级1002. 写出这个数 (20)
    PAT乙级1001. 害死人不偿命的(3n+1)猜想 (15)
    HDU 4520 小Q系列故事——最佳裁判
    POJ 3414 Pots(BFS)
    POJ 1118 Lining Up
    POJ 2484 A Funny Game
    POJ 2231 Moo Volume
    HDU 5718 Oracle(高精度)
    FZU 1502 Letter Deletion(DP)
    HDU 1564 Play a game
  • 原文地址:https://www.cnblogs.com/daijkstra/p/4057073.html
Copyright © 2011-2022 走看看