教程里说:信任我们了解了Linux体系函数之后,用C库函数来完成相似功用会感觉就简单多了。
所以测验写出相似L体系函数的文件仿制程序。
(C编程言语第二版书摘Chapter 7 – Input and Output 2中有一个运用getc,putc进行仿制的示例 )
下面是或许用到的库函数,可是用得越多犯错几率越大……
size_t fread(void *ptr, size_t size, size_t nobj, FILE *stream)
fread reads from stream into the array ptr at most nobj objects of size size. fread
returns the number of objects read; this may be less than the number requested. feof and
ferror must be used to determine status.
int feof(FILE *stream)
feof returns non-zero if the end of file indicator for stream is set.
int ferror(FILE *stream)
ferror returns non-zero if the error indicator for stream is set.
size_t fwrite(const void *ptr, size_t size, size_t nobj, FILE *stream)
fwrite writes, from the array ptr, nobj objects of size size on stream. It returns the
number of objects written, which is less than nobj on error.
int fseek(FILE *stream, long offset, int origin)
fseek sets the file position for stream; a subsequent read or write will access data beginning at
the new position. For a binary file, the position is set to offset characters from origin, which
may be SEEK_SET (beginning), SEEK_CUR (current position), or SEEK_END (end of file). For a
text stream, offset must be zero, or a value returned by ftell (in which case origin must
be SEEK_SET). fseek returns non-zero on error.
FILE *fopen(const char *filename, const char *mode)
fopen opens the named file, and returns a stream, or NULL if the attempt fails. Legal values for
mode include:
“r” open text file for reading
“w” create text file for writing; discard previous contents if any
“a” append; open or create text file for writing at end of file
“r+” open text file for update (i.e., reading and writing)
“w+” create text file for update, discard previous contents if any
“a+” append; open or create text file for update, writing at end
int fclose(FILE *stream)
fclose flushes any unwritten data for stream, discards any unread buffered input, frees any
automatically allocated buffer, then closes the stream. It returns EOF if any errors occurred, and
zero otherwise.
仿体系函数写出,许多辅佐函数没用上。履行无错,也可以将现已存在的文件(树立新文件不成功)内容仿制到另一个文件(这个文件可以成功树立)。但从被仿制新文件树立失利,可见必定经不起调试……。现在就这水平,总结以下收成吧:
1.C库函数有时运用的数据类型是特定的,例如size_t类型 ,FILE *fp等,鉴于之前的经历,想要传值,可以树立一个新的相同文件类型变量,例如FILE *fp来保存fopen的回来值。若要输出数值,可以用sizeof转化,或许测验用已知的变量类型保存,有些特定变量其实便是已知变量的类型,仅仅姓名不同。
2.fread和fwrite函数把缓冲数据分成了两个部分,一个是每个缓存块的巨细size,另一个是缓存块数量nobj(number of objects),依照网上所述的主张,每个缓存块size巨细应该取1,块数取大数,由于fread和fwrite回来的是操作的了多少数据块,不核算总数据量,这样取值便可以回来数据量(未亲身验证)。
3.我把缓存数组ptr的元素数量乱取值,超过了最大最小值将会core dumped(内存过错?)。假设依照上面的主张size取1,那么ptr数组的元素数量不能取1,会犯错……。