用C库函数写文件复制程序
教程里说:相信大家熟悉了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,会出错……。
C库函数文件复 相关文章:
- Windows CE 进程、线程和内存管理(11-09)
- RedHatLinux新手入门教程(5)(11-12)
- uClinux介绍(11-09)
- openwebmailV1.60安装教学(11-12)
- Linux嵌入式系统开发平台选型探讨(11-09)
- Windows CE 进程、线程和内存管理(二)(11-09)