int bsl_apply (const char *mod, const char *bslname) { FILE *modfile, *bslfile; unsigned char byte; char buf[4096], modname[FILENAME_MAX]; int data, nbytes, offset; strcpy (modname, mod); ucon64_file_handler (modname, NULL, 0); fcopy (mod, 0, fsizeof (mod), modname, "wb"); // no copy if one file if ((modfile = fopen (modname, "r+b")) == NULL) { fprintf (stderr, ucon64_msg[OPEN_WRITE_ERROR], modname); return -1; } if ((bslfile = fopen (bslname, "rb")) == NULL) { fprintf (stderr, ucon64_msg[OPEN_WRITE_ERROR], bslname); return -1; } printf ("Applying BSL/Baseline patch...\n"); while (!feof (bslfile)) // we could use 1, but feof() makes it fail-safe { fscanf (bslfile, "%d\n", &offset); fscanf (bslfile, "%d\n", &data); if ((offset == -1) && (data == -1)) break; fseek (modfile, offset, SEEK_SET); fputc (data, modfile); } fscanf (bslfile, "%d\n", &offset); fscanf (bslfile, "%d\n", &nbytes); fseek (modfile, offset, SEEK_SET); if (nbytes > 0) { while (nbytes > 4096) { fread (buf, 4096, 1, bslfile); fwrite (buf, 4096, 1, modfile); nbytes -= 4096; } while (nbytes-- >= 0) // yes, one byte more than the { // _value_ read from the BSL file byte = fgetc (bslfile); fputc (byte, modfile); } } printf ("Patching complete\n\n"); printf (ucon64_msg[WROTE], modname); printf ("\n" "NOTE: Sometimes you have to add/strip a 512 bytes header when you patch a ROM\n" " This means you must modify for example a SNES ROM with -swc or -stp or\n" " the patch will not work\n"); fclose (bslfile); fclose (modfile); return 0; }
void main (int argc, char **argv) { int i; if (argc != 4) { printf ("Syntax: convfont fontfile fontheight vgafontfile\n"); printf ( "\nconvfont - convert standard format binary font to codepage format\n" "The converted font is written to vgafontfile.\n"); printf ( "A binary font file of any number of characters up to 256 can be used, although\n" "at least defining the first 128 characters is a good idea. The fontheight\n" "should be in the range 1-32.\n" ); exit (1); } if ((sf = fopen (argv[1], "rb")) == NULL) { printf ("convfont: Unable to open file.\n"); exit (1); } if ((tf = fopen (argv[3], "wb")) == NULL) { printf ("convfont: Unable to create file.\n"); exit (1); } fontheight = atoi (argv[2]); if (fontheight < 1 || fontheight > 32) { printf ("convfont: Invalid fontheight.\n"); exit (1); } fseek (sf, 0, SEEK_END); sfontsize = ftell (sf); fseek (sf, 0, SEEK_SET); font_nuchars = sfontsize / fontheight; printf ("Converting %d characters\n", font_nuchars); if (font_nuchars < 1 || font_nuchars > 256) { printf ("convfont: Invalid number of characters in font.\n"); exit (1); } fread (sfontbuf, 1, sfontsize, sf); fclose (sf); for (i = 0; i < font_nuchars; i++) { int j; for (j = 0; j < fontheight; j++) tfontbuf[i * 32 + j] = sfontbuf[i * fontheight + j]; for (j = 0; j < 32 - fontheight; j++) tfontbuf[i * 32 + fontheight] = 0; } /* clear remaining characters */ for (i = font_nuchars * 32; i < 32 * 256; i++) tfontbuf[i] = 0; printf ("Writing font file.\n"); fwrite (tfontbuf, 1, 32 * 256, tf); fclose (tf); exit (0); }
size_t fp_write(const void *buf, size_t size, size_t count, void *handle) { return fwrite(buf, size, count, (FILE *)handle); }
static OPJ_SIZE_T opj_write_from_file(void *p_buffer, OPJ_SIZE_T p_nb_bytes, FILE *fp) { return fwrite(p_buffer, 1, p_nb_bytes, fp); }
int main(int argc, char* argv[]) { if (argc != 4) { printf("Usage: copy infile outfile\n"); return 1; } int n = atoi(argv[1]); if (n <= 0 || n > 100) { printf("Try again"); } // remember filenames char* infile = argv[2]; char* outfile = argv[3]; // open input file FILE* inptr = fopen(infile, "r"); if (inptr == NULL) { printf("Could not open %s.\n", infile); return 2; } // open output file FILE* outptr = fopen(outfile, "w"); if (outptr == NULL) { fclose(inptr); fprintf(stderr, "Could not create %s.\n", outfile); return 3; } // read infile's BITMAPFILEHEADER BITMAPFILEHEADER bf; fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr); // read infile's BITMAPINFOHEADER BITMAPINFOHEADER bi; fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr); // ensure infile is (likely) a 24-bit uncompressed BMP 4.0 if (bf.bfType != 0x4d42 || bf.bfOffBits != MAX || bi.biSize != 40 || bi.biBitCount != 24 || bi.biCompression != 0) { fclose(outptr); fclose(inptr); fprintf(stderr, "Unsupported file format.\n"); return 4; } int prevWidth = bi.biWidth; int prevHeight = bi.biHeight; bi.biWidth = prevWidth*n; bi.biHeight = prevHeight*n; int prevPad = (4 - (prevWidth*sizeof(RGBTRIPLE))%4)%4; int curPad = (4 - (bi.biWidth*sizeof(RGBTRIPLE))%4)%4; bi.biSizeImage = (bi.biWidth*sizeof(RGBTRIPLE)+curPad)*abs(bi.biHeight); bf.bfSize = (bi.biSizeImage)+MAX; // write outfile's BITMAPFILEHEADER fwrite(&bf,sizeof(BITMAPFILEHEADER),1,outptr); // write outfile's BITMAPINFOHEADER fwrite(&bi,sizeof(BITMAPINFOHEADER),1,outptr); int prevHeight1 = abs(prevHeight); // iterate over infile's scanlines for (int i = 0; i<prevHeight1; i++) { for (int l = 0; l<n; l++) { fseek(inptr,(MAX+((prevWidth*3+prevPad)*i)),SEEK_SET); for (int j = 0;j<prevWidth;j++) { // temporary storage RGBTRIPLE triple; // read RGB triple from infile fread(&triple, sizeof(RGBTRIPLE), 1, inptr); // write RGB triple to outfile for (int k = 0; k < n; k++) fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr); } // add curPad for (int m=0;m<curPad;m++) fputc(0x00, outptr); } } // close infile fclose(inptr); // close outfile fclose(outptr); // that's all folks return 0; }
ModelInstance::ModelInstance(MPQFile& f, char const* ModelInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE *pDirfile) { float ff[3]; f.read(&id, 4); f.read(ff, 12); pos = fixCoords(Vec3D(ff[0], ff[1], ff[2])); f.read(ff, 12); rot = Vec3D(ff[0], ff[1], ff[2]); f.read(&scale, 2); f.read(&flags, 2); // scale factor - divide by 1024. blizzard devs must be on crack, why not just use a float? sc = scale / 1024.0f; char tempname[512]; sprintf(tempname, "%s/%s", szWorkDirWmo, ModelInstName); FILE* input = fopen(tempname, "r+b"); if (!input) { //printf("ModelInstance::ModelInstance couldn't open %s\n", tempname); return; } fseek(input, 8, SEEK_SET); // get the correct no of vertices int nVertices; int count = fread(&nVertices, sizeof (int), 1, input); fclose(input); if (count != 1 || nVertices == 0) return; uint16 adtId = 0;// not used for models uint32 flags = MOD_M2; if (tileX == 65 && tileY == 65) flags |= MOD_WORLDSPAWN; //write mapID, tileX, tileY, Flags, ID, Pos, Rot, Scale, name fwrite(&mapID, sizeof(uint32), 1, pDirfile); fwrite(&tileX, sizeof(uint32), 1, pDirfile); fwrite(&tileY, sizeof(uint32), 1, pDirfile); fwrite(&flags, sizeof(uint32), 1, pDirfile); fwrite(&adtId, sizeof(uint16), 1, pDirfile); fwrite(&id, sizeof(uint32), 1, pDirfile); fwrite(&pos, sizeof(float), 3, pDirfile); fwrite(&rot, sizeof(float), 3, pDirfile); fwrite(&sc, sizeof(float), 1, pDirfile); uint32 nlen=strlen(ModelInstName); fwrite(&nlen, sizeof(uint32), 1, pDirfile); fwrite(ModelInstName, sizeof(char), nlen, pDirfile); /* int realx1 = (int) ((float) pos.x / 533.333333f); int realy1 = (int) ((float) pos.z / 533.333333f); int realx2 = (int) ((float) pos.x / 533.333333f); int realy2 = (int) ((float) pos.z / 533.333333f); fprintf(pDirfile,"%s/%s %f,%f,%f_%f,%f,%f %f %d %d %d,%d %d\n", MapName, ModelInstName, (float) pos.x, (float) pos.y, (float) pos.z, (float) rot.x, (float) rot.y, (float) rot.z, sc, nVertices, realx1, realy1, realx2, realy2 ); */ }
int main() { SHA256_CTX md_ctx; AES_KEY key; _AES_CTX ctx; uint8_t buf[64], nb[32], enb[32]; int i, len; int nk = BITS >> 5, nr = 6 + nk, key_nb = (nr + 1) * AES_NB * 4; FILE *fp, *ofp; struct timeval tv_start, tv_end; for (len = 0; len < 64; len += 32) { SHA256_Init(&md_ctx); if (len == 0) { SHA256_Update(&md_ctx, KEY, strlen(KEY)); SHA256_Final(buf, &md_ctx); } else { SHA256_Update(&md_ctx, buf + len - 32, 32); SHA256_Update(&md_ctx, KEY, strlen(KEY)); SHA256_Final(buf + len, &md_ctx); } } AES_set_encrypt_key(buf, BITS, &key); hex_dump((uint8_t *)key.rd_key, key_nb); expand_key(&(ctx.key), buf, BITS); ctx.encrypt = _AES_ecb_encrypt; ctx.decrypt = _AES_ecb_decrypt; hex_dump(ctx.key.rd_key, key_nb); for (i = 0; i < 32; i++) nb[i] = '\0'; gettimeofday(&tv_start, NULL); for (i = 0; i < 1024; i++) AES_encrypt(nb, enb, &key); gettimeofday(&tv_end, NULL); print_elapsed_time(&tv_start, &tv_end); hex_dump(enb, 16); gettimeofday(&tv_start, NULL); for (i = 0; i < 1024; i++) ctx.encrypt(nb, enb, &ctx); gettimeofday(&tv_end, NULL); print_elapsed_time(&tv_start, &tv_end); hex_dump(enb, 16); for (i = 0; i < 32; i++) nb[i] = enb[i]; ctx.decrypt(nb, enb, &ctx); hex_dump(enb, 16); if ((fp = fopen("test.bin", "r")) == NULL) { fprintf(stderr, "File open failed\n"); exit(-1); } while (!feof(fp)) { if (fread(nb, 1, _AES_BLOCK_SIZE, fp) == 0) { fprintf(stderr, "Failed in call to fread()\n"); exit(-1); } } fseek(fp, 0, SEEK_SET); i = 0; gettimeofday(&tv_start, NULL); while (!feof(fp)) { ++i; if (fread(nb, 1, _AES_BLOCK_SIZE, fp) == 0) { fprintf(stderr, "Failed in call to fread()\n"); exit(-1); } AES_encrypt(nb, enb, &key); } gettimeofday(&tv_end, NULL); print_elapsed_time(&tv_start, &tv_end); printf("blocks = %d\n", i); fseek(fp, 0, SEEK_SET); i = 0; gettimeofday(&tv_start, NULL); while (!feof(fp)) { ++i; if (fread(nb, 1, _AES_BLOCK_SIZE, fp) == 0) { fprintf(stderr, "Failed in call to fread()\n"); exit(-1); } ctx.encrypt(nb, enb, &ctx); } gettimeofday(&tv_end, NULL); print_elapsed_time(&tv_start, &tv_end); printf("blocks = %d\n", i); fclose(fp); fp = fopen("test.enc", "r"); ofp = fopen("tmp.bin", "w"); ctx.encrypt = _AES_cbc_encrypt; ctx.decrypt = _AES_cbc_decrypt; memcpy(ctx.ivec, buf + 32, _AES_BLOCK_SIZE); while (!feof(fp)) { if (fread(nb, 1, _AES_BLOCK_SIZE, fp) == 0) { fprintf(stderr, "Failed in call to fread()\n"); exit(-1); } ctx.decrypt(nb, enb, &ctx); fwrite(enb, 1, _AES_BLOCK_SIZE, ofp); } fclose(fp); fclose(ofp); return 0; }
ILint64 ILAPIENTRY myWrite (const void* data, ILuint count, ILuint size, SIO*) { return fwrite(data, count, size, writeFile); }
void data_read(int dev_fd, FILE *file_fd) { int cnt = 0; int tmp; int offs = 0; int drop = 10; /* Write TS info the file header. */ /* pktsize mode aggr_pkts_num tmstmp_offset */ sprintf(data_buff,"%d %d %d %d %d %d", TSU_TOOL_STAMP,g_buff_info.pkt_size,g_buff_info.aggr_mode, g_buff_info.aggr_num_packets, g_buff_info.aggr_mode2_tmstmp_off, g_frequency); tmp = strlen(data_buff); while(tmp < FILE_HDR_SIZE) data_buff[tmp++] = ' '; data_buff[tmp] = '\0'; if(!g_raw_mode) cnt = fwrite(data_buff,1,strlen(data_buff),file_fd); else cnt = fwrite(data_buff,1,strlen(data_buff),g_stat_fd); if(cnt != strlen(data_buff)) { fprintf(stderr,"Error wrting file header.\n"); return; } /* Calculate the values of g_ts_data_size & g_tms_data_size. */ if(g_raw_mode) { if(g_buff_info.aggr_mode == aggrMode1) { g_ts_data_size = (g_buff_info.pkt_size * g_buff_info.aggr_num_packets); g_tms_data_size = (TIMESTAMP_SIZE * g_buff_info.aggr_num_packets); } else if(g_buff_info.aggr_mode == aggrMode2) { g_ts_data_size = g_buff_info.pkt_size; g_tms_data_size = g_buff_info.aggr_mode2_tmstmp_off; } else { /* Aggregation disabled. */ g_ts_data_size = g_buff_info.pkt_size; g_tms_data_size = TIMESTAMP_SIZE; } } else { g_ts_data_size = g_data_blk_sz; g_tms_data_size = 0; } /* Setup frequency. */ if(ioctl(dev_fd,MVTSU_IOCFREQSET,&g_frequency) < 0) { fprintf(stderr,"Error configuring port frequency.\n"); goto done; } // fprintf(stderr,"g_raw_mode = %d, g_ts_data_size = %d, g_tms_data_size = %d.\n", // g_raw_mode, g_ts_data_size,g_tms_data_size); cnt = 0; while(1) { if(offs != 0) fprintf(stderr,"offs = %d.\n"); tmp = single_read_write(READ,dev_fd,data_buff + offs, g_data_blk_sz - offs); if(tmp < 0) { fprintf(stderr,"Error reading from source device / file.\n"); break; } if(drop) { drop--; continue; } cnt += tmp; if(cnt == 0) break; while(cnt >= (g_ts_data_size + g_tms_data_size)) { // fprintf(stderr,"cnt - %d, ",cnt); tmp = 0; if(g_tms_data_size > 0) { if(g_buff_info.aggr_mode == aggrMode2) { // fprintf(stderr,"TMSW = %d, ",offs); /* write only the timestamp part. */ tmp = single_fread_fwrite(WRITE,g_stat_fd, data_buff + offs, TIMESTAMP_SIZE); if(tmp < TIMESTAMP_SIZE) { fprintf(stderr,"Error writing to timestamps file.\n"); goto done; } } else { tmp = single_fread_fwrite(WRITE,g_stat_fd, data_buff + offs, g_tms_data_size); if(tmp < g_tms_data_size) { fprintf(stderr,"Error writing to timestamps file.\n"); goto done; } } offs += tmp; } // fprintf(stderr,"TSDW = %d.\n",offs); tmp = single_fread_fwrite(WRITE,file_fd,data_buff + offs, g_ts_data_size); if(tmp < g_ts_data_size) { fprintf(stderr,"Error writing to data file.\n"); goto done; } offs += g_ts_data_size; cnt -= (g_ts_data_size + g_tms_data_size); } if(cnt > 0) { memmove(data_buff,data_buff + offs, cnt); offs = cnt; } else { offs = 0; } } done: return; }
uint64 DataStream_File::Write(void* buffer, uint64 bytes) { return fwrite(buffer, size_t(bytes), 1, m_pFile); }
int main(int argc, char *argv[]) { int argchar; char* infn = NULL; char* outfn = NULL; anbool tostdout = FALSE; FILE* fin = NULL; FILE* fout = NULL; il* exts; il* sizes; int i; char* progname = argv[0]; int Next; anqfits_t* anq; exts = il_new(16); sizes = il_new(16); while ((argchar = getopt (argc, argv, OPTIONS)) != -1) switch (argchar) { case 'e': il_append(exts, atoi(optarg)); break; case 's': il_append(sizes, atoi(optarg)); break; case 'i': infn = optarg; break; case 'o': outfn = optarg; break; case '?': case 'h': printHelp(progname); return 0; default: return -1; } log_init(LOG_MSG); if (!infn || !outfn || !il_size(exts) || (il_size(exts) != il_size(sizes))) { printHelp(progname); exit(-1); } if (infn) { fin = fopen(infn, "rb"); if (!fin) { SYSERROR("Failed to open input file %s", infn); exit(-1); } } anq = anqfits_open(infn); if (!anq) { ERROR("Failed to open input file %s", infn); exit(-1); } Next = anqfits_n_ext(anq); if (Next == -1) { ERROR("Couldn't determine how many extensions are in file %s", infn); exit(-1); } else { logverb("File %s contains %i FITS extensions.\n", infn, Next); } for (i=0; i<il_size(exts); i++) { int e = il_get(exts, i); int s = il_get(sizes, i); if (e < 0 || e >= Next) { logerr("Extension %i is not valid: must be in [%i, %i]\n", e, 0, Next); exit(-1); } if (s != 2 && s != 4 && s != 8) { logerr("Invalid byte size %i: must be 2, 4, or 8.\n", s); exit(-1); } } if (!strcmp(outfn, "-")) tostdout = TRUE; if (tostdout) fout = stdout; else { fout = fopen(outfn, "wb"); if (!fout) { SYSERROR("Failed to open output file %s", outfn); exit(-1); } } for (i=0; i<Next; i++) { int hdrstart, hdrlen, datastart, datalen; int ind; int size; ind = il_index_of(exts, i); if (ind == -1) { size = 0; } else { size = il_get(sizes, ind); } hdrstart = anqfits_header_start(anq, i); hdrlen = anqfits_header_size (anq, i); datastart = anqfits_data_start(anq, i); datalen = anqfits_data_size (anq, i); if (hdrlen) { if (pipe_file_offset(fin, hdrstart, hdrlen, fout)) { ERROR("Failed to write header for extension %i", i); exit(-1); } } if (!datalen) continue; if (size) { int Nitems = datalen / size; int j; char buf[size]; logmsg("Extension %i: flipping words of length %i bytes.\n", i, size); for (j=0; j<Nitems; j++) { if (fread(buf, size, 1, fin) != 1) { SYSERROR("Failed to read data element %i from extension %i", j, i); exit(-1); } endian_swap(buf, size); if (fwrite(buf, size, 1, fout) != 1) { SYSERROR("Failed to write data element %i to extension %i", j, i); exit(-1); } } } else { logmsg("Extension %i: copying verbatim.\n", i); // passthrough if (pipe_file_offset(fin, datastart, datalen, fout)) { ERROR("Failed to write data for extension %i", i); exit(-1); } } } fclose(fin); anqfits_close(anq); if (!tostdout) fclose(fout); il_free(exts); il_free(sizes); return 0; }
int _tmain(int argc, _TCHAR* argv[]) { FILE *tFile = fopen("myfile.txt", "w+"); fprintf(tFile, "%s", "Привет мир из файла"); system("pause"); fclose(tFile); if (fopen_s(&tFile, "myFile.txt", "r")) return 0; setlocale(LC_ALL, ".1251"); char *ch = new char[100]; fseek(tFile, 0, SEEK_SET); while (!feof(tFile)) { fscanf_s(tFile, "%20s", ch, 100); printf("%s\n", ch); } system("pause"); delete[] ch; _fcloseall(); if (fopen_s(&tFile, "myFile.txt", "w+")) return 0; fprintf(tFile, "%s", "Привет опять из файла"); if (freopen_s(&tFile, "myFile.txt", "r", tFile)) return 0; ch = new char[100]; fseek(tFile, 0, SEEK_SET); while (!feof(tFile)) { fscanf_s(tFile, "%20s", ch, 100); printf("%s\n", ch); } system("pause"); delete[] ch; _fcloseall(); if (fopen_s(&tFile, "myFile.dat", "a+b")) return 0; fseek(tFile, 0, SEEK_SET); ch = new char[100]; strcpy_s(ch, 100, "Привет снова из файла"); MyStruct *str = new MyStruct; str->chislo = 10.5; str->mode = 10; str->str = new char[100]; strcpy_s(str->str, 100, ch); str->mode = strlen(str->str); fwrite(&str->chislo, sizeof(str->chislo), 1, tFile); fwrite(&str->mode, sizeof(str->mode), 1, tFile); fwrite(str->str, 1, strlen(str->str) + 1, tFile); delete[] str->str; delete str; if (freopen_s(&tFile, "myFile.dat", "r+b", tFile)) return 0; fseek(tFile, 0, SEEK_SET); str = new MyStruct; while (!feof(tFile)) { fread_s(&str->chislo, sizeof(str->chislo), sizeof(str->chislo), 1, tFile); fread_s(&str->mode, sizeof(str->mode), sizeof(str->mode), 1, tFile); fpos_t pos; fgetpos(tFile, &pos); printf("%d, %f, %d\n", str->mode, str->chislo, pos); str->str = new char[100]; fread_s(str->str, 100, 1, str->mode + 1, tFile); printf("%s\n", str->str); delete[] str->str; } delete str; system("pause"); delete[] ch; fclose(tFile); return 0; }
/* * Bareos is calling us to do the actual I/O */ static bRC pluginIO(bpContext *ctx, struct io_pkt *io) { struct plugin_ctx *p_ctx = (struct plugin_ctx *)ctx->pContext; if (!p_ctx) { return bRC_Error; } io->status = 0; io->io_errno = 0; switch(io->func) { case IO_OPEN: Dmsg(ctx, dbglvl, "bpipe-fd: IO_OPEN\n"); if (io->flags & (O_CREAT | O_WRONLY)) { char *writer_codes = apply_rp_codes(ctx); p_ctx->pfd = open_bpipe(writer_codes, 0, "w"); Dmsg(ctx, dbglvl, "bpipe-fd: IO_OPEN fd=%p writer=%s\n", p_ctx->pfd, writer_codes); if (!p_ctx->pfd) { io->io_errno = errno; Jmsg(ctx, M_FATAL, "bpipe-fd: Open pipe writer=%s failed: ERR=%s\n", writer_codes, strerror(io->io_errno)); Dmsg(ctx, dbglvl, "bpipe-fd: Open pipe writer=%s failed: ERR=%s\n", writer_codes, strerror(io->io_errno)); if (writer_codes) { free(writer_codes); } return bRC_Error; } if (writer_codes) { free(writer_codes); } } else { p_ctx->pfd = open_bpipe(p_ctx->reader, 0, "r", false); Dmsg(ctx, dbglvl, "bpipe-fd: IO_OPEN fd=%p reader=%s\n", p_ctx->pfd, p_ctx->reader); if (!p_ctx->pfd) { io->io_errno = errno; Jmsg(ctx, M_FATAL, "bpipe-fd: Open pipe reader=%s failed: ERR=%s\n", p_ctx->reader, strerror(io->io_errno)); Dmsg(ctx, dbglvl, "bpipe-fd: Open pipe reader=%s failed: ERR=%s\n", p_ctx->reader, strerror(io->io_errno)); return bRC_Error; } } sleep(1); /* let pipe connect */ break; case IO_READ: if (!p_ctx->pfd) { Jmsg(ctx, M_FATAL, "bpipe-fd: Logic error: NULL read FD\n"); Dmsg(ctx, dbglvl, "bpipe-fd: Logic error: NULL read FD\n"); return bRC_Error; } io->status = fread(io->buf, 1, io->count, p_ctx->pfd->rfd); if (io->status == 0 && ferror(p_ctx->pfd->rfd)) { io->io_errno = errno; Jmsg(ctx, M_FATAL, "bpipe-fd: Pipe read error: ERR=%s\n", strerror(io->io_errno)); Dmsg(ctx, dbglvl, "bpipe-fd: Pipe read error: ERR=%s\n", strerror(io->io_errno)); return bRC_Error; } break; case IO_WRITE: if (!p_ctx->pfd) { Jmsg(ctx, M_FATAL, "bpipe-fd: Logic error: NULL write FD\n"); Dmsg(ctx, dbglvl, "bpipe-fd: Logic error: NULL write FD\n"); return bRC_Error; } io->status = fwrite(io->buf, 1, io->count, p_ctx->pfd->wfd); if (io->status == 0 && ferror(p_ctx->pfd->wfd)) { io->io_errno = errno; Jmsg(ctx, M_FATAL, "bpipe-fd: Pipe write error: ERR=%s\n", strerror(io->io_errno)); Dmsg(ctx, dbglvl, "bpipe-fd: Pipe write error: ERR=%s\n", strerror(io->io_errno)); return bRC_Error; } break; case IO_CLOSE: if (!p_ctx->pfd) { Jmsg(ctx, M_FATAL, "bpipe-fd: Logic error: NULL FD on bpipe close\n"); Dmsg(ctx, dbglvl, "bpipe-fd: Logic error: NULL FD on bpipe close\n"); return bRC_Error; } io->status = close_bpipe(p_ctx->pfd); if (io->status) { Jmsg(ctx, M_FATAL, "bpipe-fd: Error closing stream for pseudo file %s: %d\n", p_ctx->fname, io->status); Dmsg(ctx, dbglvl, "bpipe-fd: Error closing stream for pseudo file %s: %d\n", p_ctx->fname, io->status); } break; case IO_SEEK: io->offset = p_ctx->offset; break; } return bRC_OK; }
int main(int argc,char *argv[]){ vqgen v; int entries=-1,dim=-1; int start=0,num=-1; float desired=.05f,mindist=0.f; int iter=1000; int biasp=1; int centroid=0; FILE *out=NULL; char *line; long i,j,k; int init=0; q.quant=-1; argv++; if(!*argv){ usage(); exit(0); } /* get the book name, a preexisting book to continue training */ { FILE *in=NULL; char *filename=alloca(strlen(*argv)+30),*ptr; strcpy(filename,*argv); in=fopen(filename,"r"); ptr=strrchr(filename,'-'); if(ptr){ int num; ptr++; num=atoi(ptr); sprintf(ptr,"%d.vqi",num+1); }else strcat(filename,"-0.vqi"); out=fopen(filename,"w"); if(out==NULL){ fprintf(stderr,"Unable to open %s for writing\n",filename); exit(1); } if(in){ /* we wish to suck in a preexisting book and continue to train it */ float a; line=rline(in,out,1); if(strcmp(line,vqext_booktype)){ fprintf(stderr,"wrong book type; %s!=%s\n",line,vqext_booktype); exit(1); } line=rline(in,out,1); if(sscanf(line,"%d %d %d",&entries,&dim,&vqext_aux)!=3){ fprintf(stderr,"Syntax error reading book file\n"); exit(1); } vqgen_init(&v,dim,vqext_aux,entries,mindist, vqext_metric,vqext_weight,centroid); init=1; /* quant setup */ line=rline(in,out,1); if(sscanf(line,"%ld %ld %d %d",&q.min,&q.delta, &q.quant,&q.sequencep)!=4){ fprintf(stderr,"Syntax error reading book file\n"); exit(1); } /* quantized entries */ i=0; for(j=0;j<entries;j++){ for(k=0;k<dim;k++){ line=rline(in,out,0); sscanf(line,"%f",&a); v.entrylist[i++]=a; } } vqgen_unquantize(&v,&q); /* bias */ i=0; for(j=0;j<entries;j++){ line=rline(in,out,0); sscanf(line,"%f",&a); v.bias[i++]=a; } v.seeded=1; { float *b=alloca((dim+vqext_aux)*sizeof(float)); i=0; while(1){ for(k=0;k<dim+vqext_aux;k++){ line=rline(in,out,0); if(!line)break; sscanf(line,"%f",b+k); } if(feof(in))break; vqgen_addpoint(&v,b,b+dim); } } fclose(in); } } /* get the rest... */ argv=argv++; while(*argv){ if(argv[0][0]=='-'){ /* it's an option */ if(!argv[1]){ fprintf(stderr,"Option %s missing argument.\n",argv[0]); exit(1); } switch(argv[0][1]){ case 'p': if(sscanf(argv[1],"%d,%d,%d",&entries,&dim,&q.quant)!=3) goto syner; break; case 's': if(sscanf(argv[1],"%d,%d",&start,&num)!=2){ num= -1; if(sscanf(argv[1],"%d",&start)!=1) goto syner; } break; case 'e': if(sscanf(argv[1],"%f",&desired)!=1) goto syner; break; case 'd': if(sscanf(argv[1],"%f",&mindist)!=1) goto syner; if(init)v.mindist=mindist; break; case 'i': if(sscanf(argv[1],"%d",&iter)!=1) goto syner; break; case 'b': biasp=0; break; case 'c': centroid=1; break; default: fprintf(stderr,"Unknown option %s\n",argv[0]); exit(1); } argv+=2; }else{ /* it's an input file */ char *file=strdup(*argv++); FILE *in; int cols=-1; if(!init){ if(dim==-1 || entries==-1 || q.quant==-1){ fprintf(stderr,"-p required when training a new set\n"); exit(1); } vqgen_init(&v,dim,vqext_aux,entries,mindist, vqext_metric,vqext_weight,centroid); init=1; } in=fopen(file,"r"); if(in==NULL){ fprintf(stderr,"Could not open input file %s\n",file); exit(1); } fprintf(out,"# training file entry: %s\n",file); while((line=rline(in,out,0))){ if(cols==-1){ char *temp=line; while(*temp==' ')temp++; for(cols=0;*temp;cols++){ while(*temp>32)temp++; while(*temp==' ')temp++; } fprintf(stderr,"%d colums per line in file %s\n",cols,file); } { int i; float b[cols]; if(start+num*dim>cols){ fprintf(stderr,"ran out of columns reading %s\n",file); exit(1); } while(*line==' ')line++; for(i=0;i<cols;i++){ /* static length buffer bug workaround */ char *temp=line; char old; while(*temp>32)temp++; old=temp[0]; temp[0]='\0'; b[i]=atof(line); temp[0]=old; while(*line>32)line++; while(*line==' ')line++; } if(num<=0)num=(cols-start)/dim; for(i=0;i<num;i++) vqext_addpoint_adj(&v,b,start+i*dim,dim,cols,num); } } fclose(in); } } if(!init){ fprintf(stderr,"No input files!\n"); exit(1); } vqext_preprocess(&v); /* train the book */ signal(SIGTERM,setexit); signal(SIGINT,setexit); for(i=0;i<iter && !exiting;i++){ float result; if(i!=0){ vqgen_unquantize(&v,&q); vqgen_cellmetric(&v); } result=vqgen_iterate(&v,biasp); vqext_quantize(&v,&q); if(result<desired)break; } /* save the book */ fprintf(out,"# OggVorbis VQ codebook trainer, intermediate file\n"); fprintf(out,"%s\n",vqext_booktype); fprintf(out,"%d %d %d\n",entries,dim,vqext_aux); fprintf(out,"%ld %ld %d %d\n", q.min,q.delta,q.quant,q.sequencep); /* quantized entries */ fprintf(out,"# quantized entries---\n"); i=0; for(j=0;j<entries;j++) for(k=0;k<dim;k++) fprintf(out,"%d\n",(int)(rint(v.entrylist[i++]))); fprintf(out,"# biases---\n"); i=0; for(j=0;j<entries;j++) fprintf(out,"%f\n",v.bias[i++]); /* we may have done the density limiting mesh trick; refetch the training points from the temp file */ rewind(v.asciipoints); fprintf(out,"# points---\n"); { /* sloppy, no error handling */ long bytes; char buff[4096]; while((bytes=fread(buff,1,4096,v.asciipoints))) while(bytes)bytes-=fwrite(buff,1,bytes,out); } fclose(out); fclose(v.asciipoints); vqgen_unquantize(&v,&q); vqgen_cellmetric(&v); exit(0); syner: fprintf(stderr,"Syntax error in argument '%s'\n",*argv); exit(1); }
int caps_loadtrack (uae_u16 *mfmbuf, uae_u16 *tracktiming, int drv, int track, int *tracklength, int *multirev, int *gapoffset, int *nextrev, bool sametrack) { int len; struct CapsTrackInfoT2 ci; CapsRevolutionInfo pinfo; if (tracktiming) *tracktiming = 0; if (nextrev && pCAPSSetRevolution) { if (sametrack) { pCAPSSetRevolution(caps_cont[drv], *nextrev); #if LOG_REVOLUTION write_log(_T("%03d set rev = %d\n"), track, *nextrev); #endif } else { pCAPSSetRevolution(caps_cont[drv], 0); #if LOG_REVOLUTION write_log(_T("%03d clear rev\n"), track, *nextrev); #endif } } if (!load (&ci, drv, track, true, sametrack != true)) return 0; if (pCAPSGetInfo) { if (nextrev) *nextrev = 0; pCAPSGetInfo(&pinfo, caps_cont[drv], track / 2, track & 1, cgiitRevolution, 0); #if LOG_REVOLUTION write_log(_T("%03d get next rev = %d\n"), track, pinfo.next); #endif if (nextrev && sametrack && pinfo.max > 0) *nextrev = pinfo.next; } *multirev = (ci.type & CTIT_FLAG_FLAKEY) ? 1 : 0; if (oldlib) { len = ci.tracklen * 8; *gapoffset = ci.overlap >= 0 ? ci.overlap * 8 : -1; } else { len = ci.tracklen; *gapoffset = ci.overlap >= 0 ? ci.overlap : -1; } //write_log (_T("%d %d %d %d\n"), track, len, ci.tracklen, ci.overlap); *tracklength = len; mfmcopy (mfmbuf, ci.trackbuf, len); #if 0 { FILE *f=fopen("c:\\1.txt","wb"); fwrite (ci.trackbuf, len, 1, f); fclose (f); } #endif #if CAPS_TRACKTIMING if (ci.timelen > 0 && tracktiming) { for (int i = 0; i < ci.timelen; i++) tracktiming[i] = (uae_u16)ci.timebuf[i]; } #endif #if 0 write_log (_T("caps: drive:%d track:%d len:%d multi:%d timing:%d type:%d overlap:%d\n"), drv, track, len, *multirev, ci.timelen, type, ci.overlap); #endif return 1; }
int main(int argc, const char* argv[]) { int log_tab_size = 12; int compress = 1; FSCCodingMethod method = CODING_METHOD_DEFAULT; int stats_only = 0; int ok = 0; int c; for (c = 1; c < argc; ++c) { if (!strcmp(argv[c], "-l") && c + 1 < argc) { log_tab_size = atoi(argv[++c]); if (log_tab_size > LOG_TAB_SIZE) log_tab_size = LOG_TAB_SIZE; else if (log_tab_size < 2) log_tab_size = 2; } else if (FSCParseCodingMethodOpt(argv[c], &method)) { continue; } else if (!strcmp(argv[c], "-m") && c + 1 < argc) { method = (FSCCodingMethod)atoi(argv[++c]); } else if (!strcmp(argv[c], "-s")) { stats_only = 1; } else if (!strcmp(argv[c], "-c")) { compress = 1; } else if (!strcmp(argv[c], "-d")) { compress = 0; } else if (!strcmp(argv[c], "-h")) { Help(); } } uint8_t* out = NULL; size_t out_size = 0; uint8_t* in = NULL; size_t in_size = 0; // Read input fseek(stdin, 0L, SEEK_END); in_size = ftell(stdin); fseek(stdin, 0L, SEEK_SET); if (in_size == (size_t)-1) { fprintf(stderr, "Missing/erroneous input!\n"); goto End; } in = (uint8_t*)malloc(in_size * sizeof(*in)); if (in == NULL) { fprintf(stderr, "Malloc(%lu) failed!\n", in_size); exit(-1); } ok = (fread(in, in_size, 1, stdin) == 1); if (!ok) { fprintf(stderr, "Error reading from stdin!\n"); goto End; } // Compress or decompress. MyClock start, tmp; if (compress) { // encoding GetElapsed(&start, NULL); ok = FSCEncode(in, in_size, &out, &out_size, log_tab_size, method); if (!ok) { fprintf(stderr, "ERROR while encoding!\n"); goto End; } if (stats_only) { const double elapsed = GetElapsed(&tmp, &start); const double entropy = GetEntropy(in, in_size); const double MS = 1.e-6 * in_size; const double reduction = 1. * out_size / in_size; printf("Enc time: %.3f sec [%.2lf MS/s] (%ld bytes out, %ld in).\n", elapsed, MS / elapsed, out_size, in_size); printf("Entropy: %.4lf vs expected %.4lf " "(off by %.5lf bit/symbol [%.3lf%%])\n", reduction, entropy, reduction - entropy, 100. * (reduction - entropy) / entropy); } } else { // decoding GetElapsed(&start, NULL); ok = FSCDecode(in, in_size, &out, &out_size); if (!ok) { fprintf(stderr, "ERROR while decoding!\n"); goto End; } if (stats_only) { const double elapsed = GetElapsed(&tmp, &start); const double MS = 1.e-6 * out_size; printf("Dec time: %.3f sec [%.2lf MS/s].\n", elapsed, MS / elapsed); } } if (!stats_only) { ok = (fwrite(out, out_size, 1, stdout) == 1); if (!ok) { fprintf(stderr, "Error writing to stdout!\n"); goto End; } } End: free(in); free(out); return !ok; }
int main(void) { PaStreamParameters inputParameters, outputParameters; PaStream* stream; PaError err = paNoError; paTestData data; int i; int totalFrames; int numSamples; int numBytes; SAMPLE max, val; double average; printf("patest_record.c\n"); fflush(stdout); data.maxFrameIndex = totalFrames = NUM_SECONDS * SAMPLE_RATE; /* Record for a few seconds. */ data.frameIndex = 0; numSamples = totalFrames * NUM_CHANNELS; numBytes = numSamples * sizeof(SAMPLE); data.recordedSamples = (SAMPLE *) malloc( numBytes ); /* From now on, recordedSamples is initialised. */ if( data.recordedSamples == NULL ) { printf("Could not allocate record array.\n"); goto done; } for( i=0; i<numSamples; i++ ) data.recordedSamples[i] = 0; err = Pa_Initialize(); if( err != paNoError ) goto done; inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */ if (inputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default input device.\n"); goto done; } inputParameters.channelCount = 2; /* stereo input */ inputParameters.sampleFormat = PA_SAMPLE_TYPE; inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; inputParameters.hostApiSpecificStreamInfo = NULL; /* Record some audio. -------------------------------------------- */ err = Pa_OpenStream( &stream, &inputParameters, NULL, /* &outputParameters, */ SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ recordCallback, &data ); if( err != paNoError ) goto done; err = Pa_StartStream( stream ); if( err != paNoError ) goto done; printf("\n=== Now recording!! Please speak into the microphone. ===\n"); fflush(stdout); while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) { Pa_Sleep(1000); printf("index = %d\n", data.frameIndex ); fflush(stdout); } if( err < 0 ) goto done; err = Pa_CloseStream( stream ); if( err != paNoError ) goto done; /* Measure maximum peak amplitude. */ max = 0; average = 0.0; for( i=0; i<numSamples; i++ ) { val = data.recordedSamples[i]; if( val < 0 ) val = -val; /* ABS */ if( val > max ) { max = val; } average += val; } average = average / (double)numSamples; printf("sample max amplitude = "PRINTF_S_FORMAT"\n", max ); printf("sample average = %lf\n", average ); /* Write recorded data to a file. */ #if WRITE_TO_FILE { FILE *fid; fid = fopen("recorded.raw", "wb"); if( fid == NULL ) { printf("Could not open file."); } else { fwrite( data.recordedSamples, NUM_CHANNELS * sizeof(SAMPLE), totalFrames, fid ); fclose( fid ); printf("Wrote data to 'recorded.raw'\n"); } } #endif /* Playback recorded data. -------------------------------------------- */ data.frameIndex = 0; outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ if (outputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default output device.\n"); goto done; } outputParameters.channelCount = 2; /* stereo output */ outputParameters.sampleFormat = PA_SAMPLE_TYPE; outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; printf("\n=== Now playing back. ===\n"); fflush(stdout); err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ playCallback, &data ); if( err != paNoError ) goto done; if( stream ) { err = Pa_StartStream( stream ); if( err != paNoError ) goto done; printf("Waiting for playback to finish.\n"); fflush(stdout); while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Pa_Sleep(100); if( err < 0 ) goto done; err = Pa_CloseStream( stream ); if( err != paNoError ) goto done; printf("Done.\n"); fflush(stdout); } done: Pa_Terminate(); if( data.recordedSamples ) /* Sure it is NULL or valid. */ free( data.recordedSamples ); if( err != paNoError ) { fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); err = 1; /* Always return 0 or 1, but no other return codes. */ } return err; }
void testSavers2(ILenum type, const TCHAR* targetName, const TCHAR* targetExt) { TCHAR targetFN[MAX_PATH]; // Test ilSave _tcscpy(targetFN, targetName); _tcscat(targetFN, L".ilSave."); _tcscat(targetFN, targetExt); DWORD t1 = GetTickCount(); if (!ilSave(type, targetFN)) { printf("testSavers2: Failed to save " PathCharMod " using ilSave\n", targetFN); ++errors; } DWORD t2 = GetTickCount(); printf(PathCharMod " using ilSave: %i ms\n", targetFN, t2-t1); // Test ilSaveF _tcscpy(targetFN, targetName); _tcscat(targetFN, L".ilSaveF."); _tcscat(targetFN, targetExt); FILE* file = _wfopen(targetFN, L"wb"); if (!ilSaveF(type, file)) { printf("testSavers2: Failed to save " PathCharMod " using ilSaveF\n", targetFN); ++errors; } fclose(file); // Test ilSaveL _tcscpy(targetFN, targetName); _tcscat(targetFN, L"ilSaveL."); _tcscat(targetFN, targetExt); size_t lumpSize = ilDetermineSize(type); BYTE* lump = new BYTE[lumpSize]; ILuint writtenToLump = ilSaveL(type, lump, lumpSize); if (writtenToLump > 0) { FILE* file = _wfopen(targetFN, L"wb"); size_t writtenToFile = fwrite(lump, 1, lumpSize, file); if (writtenToLump != writtenToFile) { printf("testSavers2: Failed to write " PathCharMod " after ilSaveL\n", targetFN); ++errors; } fclose(file); } else { printf("testSavers2: Failed to save " PathCharMod " using ilSaveL\n", targetFN); ++errors; } delete lump; // Test ilSaveFuncs wcscpy(targetFN, targetName); wcscat(targetFN, L".ilSaveFuncs."); wcscat(targetFN, targetExt); writeFile = _wfopen(targetFN, L"wb"); if (writeFile != NULL) { ilSetWrite(NULL, NULL, myPutc, mySeek, myTell, myWrite); if (!ilSaveFuncs(type)) printf("testSavers2: Failed to save " PathCharMod " using ilSave\n", targetFN); fclose(writeFile); } else printf("testSavers2: Failed to open " PathCharMod " for writing\n", targetFN); }
ModelInstance::ModelInstance(MPQFile& f, const char* ModelInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE* pDirfile) { float ff[3]; f.read(&id, 4); f.read(ff, 12); pos = fixCoords(Vec3D(ff[0], ff[1], ff[2])); f.read(ff, 12); rot = Vec3D(ff[0], ff[1], ff[2]); uint16 fFlags; // dummy var f.read(&scale, 2); f.read(&fFlags, 2); // unknown but flag 1 is used for biodome in Outland, currently this value is not used // scale factor - divide by 1024. blizzard devs must be on crack, why not just use a float? sc = scale / 1024.0f; char tempname[512]; sprintf(tempname, "%s/%s", szWorkDirWmo, ModelInstName); FILE* input; input = fopen(tempname, "r+b"); if (!input) { //printf("ModelInstance::ModelInstance couldn't open %s\n", tempname); return; } fseek(input, 8, SEEK_SET); // get the correct no of vertices int nVertices; fread(&nVertices, sizeof(int), 1, input); fclose(input); if (nVertices == 0) return; uint16 adtId = 0;// not used for models uint32 flags = MOD_M2; if (tileX == 65 && tileY == 65) flags |= MOD_WORLDSPAWN; //write mapID, tileX, tileY, Flags, ID, Pos, Rot, Scale, name fwrite(&mapID, sizeof(uint32), 1, pDirfile); fwrite(&tileX, sizeof(uint32), 1, pDirfile); fwrite(&tileY, sizeof(uint32), 1, pDirfile); fwrite(&flags, sizeof(uint32), 1, pDirfile); fwrite(&adtId, sizeof(uint16), 1, pDirfile); fwrite(&id, sizeof(uint32), 1, pDirfile); fwrite(&pos, sizeof(float), 3, pDirfile); fwrite(&rot, sizeof(float), 3, pDirfile); fwrite(&sc, sizeof(float), 1, pDirfile); uint32 nlen = strlen(ModelInstName); fwrite(&nlen, sizeof(uint32), 1, pDirfile); fwrite(ModelInstName, sizeof(char), nlen, pDirfile); }
static int gunzip_and_replace(geoipupdate_s * gu, const char *gzipfile, const char *geoip_filename, const char *expected_file_md5) { gzFile gz_fh; FILE *fh = fopen(gzipfile, "rb"); exit_if(NULL == fh, "Can't open %s\n", gzipfile); size_t bsize = 8096; char *buffer = (char *)xmalloc(bsize); ssize_t read_bytes = my_getline(&buffer, &bsize, fh); exit_if(-1 == fclose(fh), "Error closing stream: %s", strerror(errno)); if (read_bytes < 0) { fprintf(stderr, "Read error %s\n", gzipfile); unlink(gzipfile); free(buffer); return ERROR; } const char *no_new_upd = "No new updates available"; if (!strncmp(no_new_upd, buffer, strlen(no_new_upd))) { say_if(gu->verbose, "%s\n", no_new_upd); unlink(gzipfile); free(buffer); return OK; } if (strncmp(buffer, "\x1f\x8b", 2)) { // error not a zip file unlink(gzipfile); printf("%s is not a valid gzip file\n", gzipfile); return ERROR; } // We do this here as we have to check that there is an update before // we check for the header. exit_unless( 32 == strnlen(expected_file_md5, 33), "Did not receive a valid expected database MD5 from server\n"); char *file_path_test; xasprintf(&file_path_test, "%s.test", geoip_filename); say_if(gu->verbose, "Uncompress file %s to %s\n", gzipfile, file_path_test); gz_fh = gzopen(gzipfile, "rb"); exit_if(gz_fh == NULL, "Can't open %s\n", gzipfile); FILE *fhw = fopen(file_path_test, "wb"); exit_if(fhw == NULL, "Can't open %s\n", file_path_test); for (;; ) { int amt = gzread(gz_fh, buffer, bsize); if (amt == 0) { break; // EOF } exit_if(amt == -1, "Gzip read error while reading from %s\n", gzipfile); exit_unless(fwrite(buffer, 1, amt, fhw) == (size_t)amt, "Gzip write error\n"); } exit_if(-1 == fclose(fhw), "Error closing stream: %s", strerror(errno)); exit_if(gzclose(gz_fh) != Z_OK, "Gzip read error while closing from %s\n", gzipfile); free(buffer); char actual_md5[33]; md5hex(file_path_test, actual_md5); exit_if(strncasecmp(actual_md5, expected_file_md5, 32), "MD5 of new database (%s) does not match expected MD5 (%s)", actual_md5, expected_file_md5); say_if(gu->verbose, "Rename %s to %s\n", file_path_test, geoip_filename); int err = rename(file_path_test, geoip_filename); exit_if(err, "Rename %s to %s failed\n", file_path_test, geoip_filename); // fsync directory to ensure the rename is durable int dirfd = open(gu->database_dir, O_DIRECTORY); exit_if(-1 == dirfd, "Error opening database directory: %s", strerror(errno)); exit_if(-1 == fsync(dirfd), "Error syncing database directory: %s", strerror(errno)); exit_if(-1 == close(dirfd), "Error closing database directory: %s", strerror(errno)); exit_if(-1 == unlink(gzipfile), "Error unlinking %s: %s", gzipfile, strerror(errno)); free(file_path_test); return OK; }
// this makes sure that // image size is written in correct format // and byte order (least first) IGL_INLINE void write16bit(int n, FILE* fp) { unsigned char bytes[] = { static_cast<unsigned char>(n % 256), static_cast<unsigned char>(n / 256) }; fwrite(bytes, 2, sizeof(unsigned char),fp); }
bool Model::ConvertToVMAPModel(const char * outfilename) { int N[12] = {0,0,0,0,0,0,0,0,0,0,0,0}; FILE* output=fopen(outfilename, "wb"); if (!output) { printf("Can't create the output file '%s'\n",outfilename); return false; } fwrite(szRawVMAPMagic, 8, 1, output); uint32 nVertices = header.nBoundingVertices; fwrite(&nVertices, sizeof(int), 1, output); uint32 nofgroups = 1; fwrite(&nofgroups,sizeof(uint32), 1, output); fwrite(N,4*3,1,output);// rootwmoid, flags, groupid fwrite(N,sizeof(float),3*2,output);//bbox, only needed for WMO currently fwrite(N,4,1,output);// liquidflags fwrite("GRP ",4,1,output); uint32 branches = 1; int wsize; wsize = sizeof(branches) + sizeof(uint32) * branches; fwrite(&wsize, sizeof(int), 1, output); fwrite(&branches,sizeof(branches), 1, output); uint32 nIndexes = header.nBoundingTriangles; fwrite(&nIndexes,sizeof(uint32), 1, output); fwrite("INDX",4, 1, output); wsize = sizeof(uint32) + sizeof(unsigned short) * nIndexes; fwrite(&wsize, sizeof(int), 1, output); fwrite(&nIndexes, sizeof(uint32), 1, output); if (nIndexes > 0) { for (uint32 i = 0; i < nIndexes; ++i) { if ((i % 3) - 1 == 0 && i + 1 < nIndexes) { uint16 tmp = indices[i]; indices[i] = indices[i + 1]; indices[i + 1] = tmp; } } fwrite(indices, sizeof(unsigned short), nIndexes, output); } fwrite("VERT", 4, 1, output); wsize = sizeof(int) + sizeof(float) * 3 * nVertices; fwrite(&wsize, sizeof(int), 1, output); fwrite(&nVertices, sizeof(int), 1, output); if (nVertices >0) { for (uint32 vpos = 0; vpos < nVertices; ++vpos) { float tmp = vertices[vpos].y; vertices[vpos].y = -vertices[vpos].z; vertices[vpos].z = tmp; } fwrite(vertices, sizeof(float)*3, nVertices, output); } fclose(output); return true; }
int crm_expr_correlate_learn(CSL_CELL *csl, ARGPARSE_BLOCK *apb, VHT_CELL **vht, CSL_CELL *tdw, char *txtptr, int txtstart, int txtlen) { // learn the given text as correlative text // belonging to a particular type. // learn <flags> (classname) /regex/ (regex is ignored) // int i, j, k; char ptext[MAX_PATTERN]; // the regex pattern int plen; char ltext[MAX_PATTERN]; // the variable to learn int llen; char htext[MAX_PATTERN]; // the hash name int hlen; int cflags, eflags; struct stat statbuf; // for statting the hash file FILE *f; // hashfile fd // //regex_t regcb; int textoffset; int textlen; int sense; int vhtindex; int microgroom; int fev; int made_new_file; char *learnfilename; if (internal_trace) fprintf(stderr, "executing a LEARN (correlation format)\n"); // Keep the gcc compiler from complaining about unused variables // i = hctable[0]; // extract the hash file name hlen = crm_get_pgm_arg(htext, MAX_PATTERN, apb->p1start, apb->p1len); hlen = crm_nexpandvar(htext, hlen, MAX_PATTERN, vht, tdw); // // extract the variable name (if present) llen = crm_get_pgm_arg(ltext, MAX_PATTERN, apb->b1start, apb->b1len); llen = crm_nexpandvar(ltext, llen, MAX_PATTERN, vht, tdw); // get the "this is a word" regex plen = crm_get_pgm_arg(ptext, MAX_PATTERN, apb->s1start, apb->s1len); plen = crm_nexpandvar(ptext, plen, MAX_PATTERN, vht, tdw); // set our cflags, if needed. The defaults are // "case" and "affirm", (both zero valued). // and "microgroom" disabled. cflags = REG_EXTENDED; eflags = 0; sense = +1; if (apb->sflags & CRM_NOCASE) { cflags = cflags | REG_ICASE; eflags = 1; if (user_trace) fprintf(stderr, "turning oncase-insensitive match\n"); } if (apb->sflags & CRM_REFUTE) { sense = -sense; if (user_trace) fprintf(stderr, " refuting learning\n"); } microgroom = 0; if (apb->sflags & CRM_MICROGROOM) { microgroom = 1; if (user_trace) fprintf(stderr, " enabling microgrooming.\n"); } // // grab the filename, and stat the file // note that neither "stat", "fopen", nor "open" are // fully 8-bit or wchar clean... if (!crm_nextword(htext, hlen, 0, &i, &j) || j == 0) { fev = nonfatalerror_ex(SRC_LOC(), "\nYou didn't specify a valid filename: '%.*s'\n", (int)hlen, htext); return fev; } j += i; CRM_ASSERT(i < hlen); CRM_ASSERT(j <= hlen); // filename starts at i, ends at j. null terminate it. htext[j] = 0; learnfilename = &htext[i]; if (!learnfilename) { untrappableerror("Cannot allocate classifier memory", "Stick a fork in us; we're _done_."); } // and stat it to get it's length k = stat(learnfilename, &statbuf); made_new_file = 0; // quick check- does the file even exist? if (k != 0) { // file didn't exist... create it CRM_PORTA_HEADER_INFO classifier_info = { 0 }; if (user_trace) { fprintf(stderr, "\nCreating new correlate file %s\n", learnfilename); fprintf(stderr, "Opening file %s for write\n", learnfilename); } f = fopen(learnfilename, "wb"); if (!f) { char dirbuf[DIRBUFSIZE_MAX]; fev = fatalerror_ex(SRC_LOC(), "\n Couldn't open your new CORRELATE file %s for writing; (full path: '%s') errno=%d(%s)\n", learnfilename, mk_absolute_path(dirbuf, WIDTHOF(dirbuf), learnfilename), errno, errno_descr(errno)); return fev; } classifier_info.classifier_bits = CRM_CORRELATE; classifier_info.hash_version_in_use = selected_hashfunction; if (0 != fwrite_crm_headerblock(f, &classifier_info, NULL)) { fev = nonfatalerror_ex(SRC_LOC(), "\n Couldn't write header to file %s; errno=%d(%s)\n", learnfilename, errno, errno_descr(errno)); fclose(f); return fev; } // file_memset(f, 0, count); // don't do any output at all. made_new_file = 1; statbuf.st_size = 0; } else { if (user_trace) { fprintf(stderr, "Opening correlate file %s for append\n", learnfilename); } // Now a nasty bit. Because there might be data of the // file retained, we need to force an unmap-by-name which will allow a remap // with the new file length later on. if (internal_trace) { fprintf(stderr, "un-mmap-ping file %s for known state\n", learnfilename); } crm_force_munmap_filename(learnfilename); f = fopen(learnfilename, "ab+"); if (!f) { char dirbuf[DIRBUFSIZE_MAX]; fev = fatalerror_ex(SRC_LOC(), "\n Couldn't open your CORRELATE file %s for append; (full path: '%s') errno=%d(%s)\n", learnfilename, mk_absolute_path(dirbuf, WIDTHOF(dirbuf), learnfilename), errno, errno_descr(errno)); return fev; } if (is_crm_headered_file(f)) { statbuf.st_size -= CRM114_HEADERBLOCK_SIZE; } // And make sure the file pointer is at EOF. (void)fseek(f, 0, SEEK_END); if (ftell(f) == 0) { CRM_PORTA_HEADER_INFO classifier_info = { 0 }; classifier_info.classifier_bits = CRM_CORRELATE; classifier_info.hash_version_in_use = selected_hashfunction; if (0 != fwrite_crm_headerblock(f, &classifier_info, NULL)) { int err = errno; fclose(f); fev = nonfatalerror_ex(SRC_LOC(), "Couldn't write the header to the .hypsvm file named '%s': error %d(%s)", learnfilename, err, errno_descr(err)); return fev; } // file_memset(f, 0, count); // don't do any output at all. made_new_file = 1; statbuf.st_size = 0; } } // if (user_trace) { fprintf(stderr, "Correlation text file %s has length %d characters\n", learnfilename, (int)(statbuf.st_size / sizeof(FEATUREBUCKET_TYPE))); } // // get the text to "learn" (well, append to the correlation file) // // This is the text that we'll append to the correlation file. /* removed i=0: re-init here: important! */ if (llen > 0) { if (!crm_is_legal_variable(ltext, llen)) { int q = fatalerror_ex(SRC_LOC(), "Attempt to LEARN from an illegal variable '%.*s'. How very bizarre.", llen, ltext); return q; } vhtindex = crm_vht_lookup(vht, ltext, llen, csl->calldepth); } else { vhtindex = crm_vht_lookup(vht, ":_dw:", 5, csl->calldepth); } if (vht[vhtindex] == NULL) { int q; CRM_ASSERT(f != NULL); fclose(f); q = nonfatalerror(" Attempt to LEARN from a nonexistent variable ", ltext); return q; } mdw = NULL; if (tdw->filetext == vht[vhtindex]->valtxt) mdw = tdw; if (cdw->filetext == vht[vhtindex]->valtxt) mdw = cdw; if (mdw == NULL) { int q; CRM_ASSERT(f != NULL); fclose(f); q = nonfatalerror(" Bogus text block containing variable ", ltext); return q; } else { ssize_t old_fileoffset; textoffset = vht[vhtindex]->vstart; textlen = vht[vhtindex]->vlen; if (user_trace) { fprintf(stderr, "learning the text (len %d) :", textlen); fwrite4stdio(&(mdw->filetext[textoffset]), ((textlen < 128) ? textlen : 128), stderr); fprintf(stderr, "\n"); } // append the "learn" text to the end of the file. // CRM_ASSERT(f != NULL); (void)fseek(f, 0, SEEK_END); old_fileoffset = ftell(f); if (textlen != fwrite(&(mdw->filetext[textoffset]), 1, textlen, f)) { int fev; int err = errno; fclose(f); // try to correct the failure by ditching the new, partially(?) written(?) data truncate(learnfilename, old_fileoffset); fev = nonfatalerror_ex(SRC_LOC(), "Failed to append the 'learn' text to the correlation file '%s': error %d(%s)\n", learnfilename, err, errno_descr(err)); return fev; } } CRM_ASSERT(f != NULL); fclose(f); return 0; }