码迷,mamicode.com
首页 > 其他好文 > 详细

APUE5.9二进制IO 输入输出流理解

时间:2015-01-30 15:15:29      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

技术分享

可以看出fopen函数是用来打开流的,返回值是一个指向文件对象的指针。

 

通过下面的例子可以知道,fd的使用与对象stdcin,stdcout一样,所以我认为在unix/linux中,对象stdin,stdout的类型应该也是FILE*类型。

也就是说stdin,stdout,这两个对象,是输入流与流出流被fopen后,返回的像fd一样的FILE*对象。

fopen函数是用来打开文件的,通过指定文件名,像下例一样,书中说fopen用来打开流,说白了,流也是一个文件,对于类UNIX操作系统来说,这样就统一了一些关于UNIX的理解,流,文件,文件指针,流对象。

man 3 stdin证实了我的想法

技术分享

 
#include <iostream>

#include <stdio.h>

using std::cerr;
using std::cout;
using std::cin;
using std::endl;

class item{
public:
    item() : a(0), b(0.0), c(‘\0‘) { }
    int a;
    float b;
    char c;
};

int main()
{
    item i;
    i.b = 10.00;

    // size_t fwrite(const void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp);
    // write the object i to standard output
    if(1 != fwrite(&i, sizeof(i), 1, stdout))
    {
        fwrite(&i, sizeof(i), 1, stdout);
    }

    cout << endl;

    // FILE *fopen(const char *restrict pathname, const char *restrict type);
    FILE* fd = fopen("a.txt", "rb+");

    if (NULL == fd)
    {
        cerr << "fopen failed" << endl;
    }

    // write the object i to file in hard disk
    // compared to "fwrite(&i, sizeof(i), 1, stdout);
    // i think stdout is a object of type FILE*, because stdout is just like variable fd
    // this is important for us to understand what is stream

    if(1 != fwrite(&i, sizeof(i), 1, fd))
    {
        cerr << "fwrite failed, when writting to a.txt" << endl;
    }

    fclose(fd);

    fd = fopen("a.txt", "rb+");
    if (NULL == fd)
    {
        cerr << "fopen failed when open the second time" << endl;
    }
    item j;
    cout << "before fread function, j.b =: " << j.b << endl;
    // size_t fread(void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp);
    if (1 != fread(&j, sizeof(item), 1, fd))
    {
        cerr << "fread failed" << endl;
    }
    else
    {
        cout << "after fread function, j.b =: " << j.b << endl;
    }

    return 0;
}
all: freadfwrite
freadfwrite: freadfwrite.cpp
	g++ -g -Wall freadfwrite.cpp ../lib/libapue.a -I ../include -o freadfwrite
clean:
	rm freadfwrite

技术分享

 

技术分享

 

 

技术分享

APUE5.9二进制IO 输入输出流理解

标签:

原文地址:http://www.cnblogs.com/sunyongjie1984/p/test.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!