- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <stdio.h>
- #include <errno.h>
- #define BUFFER_SIZE 1024
- int main(int argc,char **argv)
- {
- int from_fd,to_fd;
- int bytes_read,bytes_write;
- char buffer[BUFFER_SIZE];
- char *ptr;
- if(argc!=3)
- {
- fprintf(stderr,"Usage:%s fromfile tofile/n/a",argv[0]);
- exit(1);
- }
- /* 打开源文件 */
- if((from_fd=open(argv[1],O_RDONLY))==-1)
- {
- fprintf(stderr,"Open %s Error:%s/n",argv[1],strerror(errno));
- exit(1);
- }
- /* 创建目的文件 */
- if((to_fd=open(argv[2],O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR))==-1)
- {
- fprintf(stderr,"Open %s Error:%s/n",argv[2],strerror(errno));
- exit(1);
- }
- /* 以下代码是一个经典的拷贝文件的代码 */
- while(bytes_read=read(from_fd,buffer,BUFFER_SIZE))
- {
- /* 一个致命的错误发生了 */
- if((bytes_read==-1)&&(errno!=EINTR)) break;
- else if(bytes_read>0)
- {
- ptr=buffer;
- while(bytes_write=write(to_fd,ptr,bytes_read))
- {
- /* 一个致命错误发生了 */
- if((bytes_write==-1)&&(errno!=EINTR))break;
- /* 写完了所有读的字节 */
- else if(bytes_write==bytes_read) break;
- /* 只写了一部分,继续写 */
- else if(bytes_write>0)
- {
- ptr+=bytes_write;
- bytes_read-=bytes_write;
- }
- }
- /* 写的时候发生的致命错误 */
- if(bytes_write==-1)break;
- }
- }
- close(from_fd);
- close(to_fd);
- exit(0);
- }
lseek对应的应该open打开操作文件,例子:
函数名称: lseek
函数原型: long lseek(int handle,long offset,int fromwhere)
函数功能: 移动文件位置指针到指定位置
函数返回:
参数说明: handle-文件句柄,offset-文件位置,fromwhere-从文件何处开始移动,该参数可使用以下宏定义:
SEEK_SET-0从文件开始位置计算offset
SEEK_CUR-1从当前位置计算offset
SEEK_END-2从文件结束位置计算offset,此时offset为负数
所属文件:
- #include <sys\stat.h>
- #include <string.h>
- #include <stdio.h>
- #include <fcntl.h>
- #include <io.h>
- int main()
- {
- int handle;
- char msg[]="This is a test";
- char ch;
- handle=open("TEST.$$$",O_CREAT | O_RDWR,S_IREAD | S_IWRITE);
- write(handle,msg,strlen(msg));
- lseek(handle,0L,SEEK_SET);
- do{
- read(handle,&ch,1);
- printf("%c",ch);
- }while (!eof(handle));
- close(handle);
- return 0;
- }
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/stat.h>
- #include <unistd.h>
- int main()
- {
- char result[100];
- FILE *fp = NULL;
- int fd = 0;
- int off = 0;
- fp = fopen("t.txt", "r");
- fd = fileno(fp);
- off = lseek(fd, 10, SEEK_SET);
- printf("off=%d\n", off);
- fscanf(fp, "%s\n", result);
- printf("%s\n", result);
- fseek(fp, 0, SEEK_SET); /*文件指针回到文件起始处*/
- off = lseek(fd, 0, SEEK_SET);
- printf("off=%d\n", off);
- fscanf(fp, "%s\n", result);
- printf("%s\n", result);
- fclose(fp);
- return 0;
- }
阅读(1096) | 评论(0) | 转发(0) |