资源描述:
《c语言实现读写二进制文件》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、C语言实现myql中存取二进制文件include#include#include#include#include#include#definehost"localhost"//mysqlserver#defineusername"root"#definepassword"cipher"#definedatabase"www"intget_file_size(char*path,off_t*size){structstatfil
2、e_stats;if(stat(path,&file_stats))return-1;*size=file_stats.st_size;return0;}intmain(intargc,char*argv[]){char*filename;off_t*size;MYSQL*conn;MYSQL_RES*res_set;MYSQL_ROWrow;MYSQL_FIELD*field;inti,flag;char*sql;FILE*fp;char*buf;intn=0;char*end;unsignedlong*length;if(argc!=2){printf("
3、Usage:%ssrcfile",argv[0]);exit(1);}filename=argv[1];if((get_file_size(filename,size))==-1){13 perror("getfilesize");exit(1);}if((buf=(char*)malloc(sizeof(char)*(*size+1)))==NULL){perror("mallocbuf");exit(1);}if((fp=fopen(filename,"rb"))==NULL){perror("fopenfile");exit(1);}if(
4、(n=fread(buf,1,*size,fp))<0){//n=*sizeperror("freadfile");exit(1);}sql=(char*)malloc(sizeof(char)*n*2+256);//2n+1+strlen(othersql)if(sql==NULL){perror("mallocsql");exit(1);}conn=mysql_init(NULL);if(conn==NULL){printf("initmysql,%s",mysql_error(conn));exit(1);}if((mysql_real_connec
5、t(conn,host,username,password,database,0,NULL,0))==NULL){printf("connectmysql,%s",mysql_error(conn));exit(1);}strcpy(sql,"insertintowww(id,name,file)values(5,'peter',");end=sql;end+=strlen(sql);//pointsqltail//convertNUL(ASCII0)、''、'r'、''’、'''、'"'和Control-Zandsoon*end++=''';e
6、nd+=mysql_real_escape_string(conn,end,buf,n);*end++=''';*end++=')';flag=mysql_real_query(conn,sql,(unsignedint)(end-sql));if(flag!=0){printf("insertfailed,%s",mysql_error(conn));exit(1);13}if((mysql_real_query(conn,"SELECTfileFROMwwwwhereid=5",31))!=0){printf("insertfailed,%s",
7、mysql_error(conn));exit(1);}res_set=mysql_store_result(conn);fclose(fp);fp=NULL;fp=fopen("foo.bk","wb");while((row=mysql_fetch_row(res_set))!=NULL){length=mysql_fetch_lengths(res_set);for(i=0;i8、n);free(sql);sql=NU