可以看出fopen函数是用来打开流(其实应该是说用来打开文件的)的,返回值是一个指向文件对象的指针。
通过下面的例子可以知道,fd的使用与对象stdcin,stdcout一样,所以我认为在unix/linux中,对象stdin,stdout的类型应该也是FILE*类型。
也就是说stdin,stdout,这两个对象,是输入流与流出流(各种流应该也就是一个UNIX文件)被fopen后,返回的像fd一样的FILE*对象。
fopen函数是用来打开文件的,通过指定文件名,像下例一样,书中说fopen用来打开流,说白了,流也是一个文件,对于类UNIX操作系统来说,这样就统一了一些关于UNIX的理解,流,文件,文件指针,流对象。
man 3 stdin证实了我的想法
// 5-9 program apue/5/freadfwrite.cpp
#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(' ') { }
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

![V2]43K7)5}(E6MHLHRG7Z7I V2]43K7)5}(E6MHLHRG7Z7I](http://images0.cnblogs.com/blog/405501/201501/301312294412581.png)

![_Z}R]J7R$S}CLD1T%PK4@X0 _Z}R]J7R$S}CLD1T%PK4@X0](http://images0.cnblogs.com/blog/405501/201501/301258528622745.png)

