以下代码演示如果取得文件"/data/temp.jpg”大小及读取文件前256Bytes
Code#include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <sys/stat.h> int main() { int fbfd = 0; int size,nread,n; char c,buffer[256]; struct stat buf; if (stat("/data/temp.jpg",&buf)<0) { printf("can't get file infomation."); return (0); } size = buf.st_size; fbfd = open("/data/temp.jpg", O_RDONLY); if (!fbfd) { printf("Error: cannot open file.\n"); return(1); } /* // 这也是一种取得文件大小的方法,不过很条 size = 0; while ( (nread = read(fbfd,buffer,sizeof(buffer))) > 0) { size += nread; } */ printf("Size=%d\n",size); lseek(fbfd,0,SEEK_SET); //while(1) { nread = read(fbfd,buffer,256); if(nread > 0) { for(n=0;n<nread;n++) { printf("%c",buffer[n]); } printf("\n"); } else { printf("Read error, nread=%d\n",nread); //break; } } printf("Read end\n"); return (0); }在Android2.1 Emulator上输出如下: