UNIX环境高级编程5.9二进制IO 输入输出流理解
可以看出fopen函数是用来打开流(其实应该是说用来打开文件的)的,返回值是一个指向文件对象的指针。
通过下面的例子可以知道,fd的使用与对象stdcin,stdcout一样,所以我认为在unix/linux中,对象stdin,stdout的类型应该也是FILE*类型。
也就是说stdin,stdout,这两个对象,是输入流与流出流(各种流应该也就是一个UNIX文件)被fopen后,返回的像fd一样的FILE*对象。
fopen函数是用来打开文件的,通过指定文件名,像下例一样,书中说fopen用来打开流,说白了,流也是一个文件,对于类UNIX操作系统来说,这样就统一了一些关于UNIX的理解,流,文件,文件指针,流对象。
man 3 stdin证实了我的想法
1 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | // 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( '\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; } |
1 | |
1 2 3 4 5 | all: freadfwrite freadfwrite: freadfwrite.cpp g++ -g -Wall freadfwrite.cpp ../lib/libapue.a -I ../include -o freadfwrite clean: rm freadfwrite |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步