Exemple #1
0
gliGenericImage *
gliReadTGA(FILE *fp, char *name)
{
  TgaHeader tgaHeader;
  TgaFooter tgaFooter;
  char horzrev, vertrev;
  int width, height, bpp;
  int start, end, dir;
  int i, j, k;
  int pelbytes, wbytes;
  GLenum format;
  int components;
  RLEstate rleRec;
  RLEstate *rleInfo;
  int rle;
  int index, colors, length;
  GLubyte *cmap, *pixels, *data;
  int (*myfread)(RLEstate *rleInfo, void*, size_t, size_t, FILE*);
  gliGenericImage *genericImage;

  /* Check the footer. */
  if (fseek(fp, 0L - sizeof(tgaFooter), SEEK_END)
      || fread(&tgaFooter, sizeof(tgaFooter), 1, fp) != 1) {
    sprintf(error, "TGA: Cannot read footer from \"%s\"", name);
    if (verbose) printf("%s\n", error);
    return NULL;
  }  

  /* Check the signature. */
  if (memcmp(tgaFooter.signature, TGA_SIGNATURE,
             sizeof(tgaFooter.signature)) == 0) {
    if (verbose) printf("TGA: found New TGA\n");
  } else {
    if (verbose) printf("TGA: found Original TGA\n");
  }

  if (fseek(fp, 0, SEEK_SET) ||
      fread(&tgaHeader, sizeof(tgaHeader), 1, fp) != 1) {
    sprintf(error, "TGA: Cannot read header from \"%s\"", name);
    if (verbose) printf("%s\n", error);
    return NULL;
  }

  if (verbose && tgaHeader.idLength) {
    char *idString = (char*) malloc(tgaHeader.idLength);
    
    if (fread(idString, tgaHeader.idLength, 1, fp) != 1) {
      sprintf(error, "TGA: Cannot read ID field in \"%s\"", name);
      printf("%s\n", error);
    } else {
      printf("TGA: ID field: \"%*s\"\n", tgaHeader.idLength, idString);
    }
    free(idString);
  } else {
    /* Skip the image ID field. */
    if (tgaHeader.idLength && fseek(fp, tgaHeader.idLength, SEEK_CUR)) {
      sprintf(error, "TGA: Cannot skip ID field in \"%s\"", name);
      if (verbose) printf("%s\n", error);
      return NULL;
    }
  }
  
  /* Reassemble the multi-byte values correctly, regardless of
     host endianness. */
  width = (tgaHeader.widthHi << 8) | tgaHeader.widthLo;
  height = (tgaHeader.heightHi << 8) | tgaHeader.heightLo;
  bpp = tgaHeader.bpp;
  if (verbose) {
    printf("TGA: width=%d, height=%d, bpp=%d\n", width, height, bpp);
  }

  horzrev = tgaHeader.descriptor & TGA_DESC_HORIZONTAL;
  vertrev = !(tgaHeader.descriptor & TGA_DESC_VERTICAL);
  if (verbose && horzrev) printf("TGA: horizontal reversed\n");
  if (verbose && vertrev) printf("TGA: vertical reversed\n");

  rle = 0;
  switch (tgaHeader.imageType) {
  case TGA_TYPE_MAPPED_RLE:
    rle = 1;
    if (verbose) printf("TGA: run-length encoded\n");
  case TGA_TYPE_MAPPED:
    /* Test for alpha channel. */
    format = GL_COLOR_INDEX;
    components = 1;
    if (verbose) {
      printf("TGA: %d bit indexed image (%d bit palette)\n",
        tgaHeader.colorMapSize, bpp);
    }
    break;

  case TGA_TYPE_GRAY_RLE:
    rle = 1;
    if (verbose) printf("TGA: run-length encoded\n");
  case TGA_TYPE_GRAY:
    format = GL_LUMINANCE;
    components = 1;
    if (verbose) printf("TGA: %d bit grayscale image\n", bpp);
    break;

  case TGA_TYPE_COLOR_RLE:
    rle = 1;
    if (verbose) printf("TGA: run-length encoded\n");
  case TGA_TYPE_COLOR:
    /* Test for alpha channel. */
    if (bpp == 32) {
      format = GL_BGRA_EXT;
      components = 4;
      if (verbose) {
        printf("TGA: %d bit color image with alpha channel\n", bpp);
      }
    } else {
      format = GL_BGR_EXT;
      components = 3;
      if (verbose) printf("TGA: %d bit color image\n", bpp);
    }
    break;

  default:
    sprintf(error,
      "TGA: unrecognized image type %d\n", tgaHeader.imageType);
    if (verbose) printf("%s\n", error);
    return NULL;
  }

  if ((format == GL_BGRA_EXT && bpp != 32) ||
      (format == GL_BGR_EXT && bpp != 24) ||
      ((format == GL_LUMINANCE || format == GL_COLOR_INDEX) && bpp != 8)) {
    /* FIXME: We haven't implemented bit-packed fields yet. */
    sprintf(error, "TGA: channel sizes other than 8 bits are unimplemented");
    if (verbose) printf("%s\n", error);
    return NULL;
  }

  /* Check that we have a color map only when we need it. */
  if (format == GL_COLOR_INDEX) {
    if (tgaHeader.colorMapType != 1) {
      sprintf(error, "TGA: indexed image has invalid color map type %d\n",
        tgaHeader.colorMapType);
      if (verbose) printf("%s\n", error);
      return NULL;
    }
  } else if (tgaHeader.colorMapType != 0) {
    sprintf(error, "TGA: non-indexed image has invalid color map type %d\n",
      tgaHeader.colorMapType);
    if (verbose) printf("%s\n", error);
    return NULL;
  }

  if (tgaHeader.colorMapType == 1) {
    /* We need to read in the colormap. */
    index = (tgaHeader.colorMapIndexHi << 8) | tgaHeader.colorMapIndexLo;
    length = (tgaHeader.colorMapLengthHi << 8) | tgaHeader.colorMapLengthLo;

    if (verbose) {
      printf("TGA: reading color map (%d + %d) * (%d / 8)\n",
        index, length, tgaHeader.colorMapSize);
    }
    if (length == 0) {
      sprintf(error, "TGA: invalid color map length %d", length);
      if (verbose) printf("%s\n", error);
      return NULL;
    }
    if (tgaHeader.colorMapSize != 24) {
      /* We haven't implemented bit-packed fields yet. */
      sprintf(error, "TGA: channel sizes other than 8 bits are unimplemented");
      if (verbose) printf("%s\n", error);
      return NULL;
    }

    pelbytes = tgaHeader.colorMapSize / 8;
    colors = length + index;
    cmap = malloc (colors * pelbytes);

    /* Zero the entries up to the beginning of the map. */
    memset(cmap, 0, index * pelbytes);

    /* Read in the rest of the colormap. */
    if (fread(cmap, pelbytes, length, fp) != (size_t) length) {
      sprintf(error, "TGA: error reading colormap (ftell == %ld)\n",
        ftell (fp));
      if (verbose) printf("%s\n", error);
      return NULL;
    }

    if (pelbytes >= 3) {
      /* Rearrange the colors from BGR to RGB. */
      int tmp;
      for (j = index; j < length * pelbytes; j += pelbytes) {
        tmp = cmap[j];
        cmap[j] = cmap[j + 2];
        cmap[j + 2] = tmp;
      }
    }
  } else {
    colors = 0;
    cmap = NULL;
  }

  /* Allocate the data. */
  pelbytes = bpp / 8;
  pixels = (unsigned char *) malloc (width * height * pelbytes);

  if (rle) {
    rleRec.statebuf = 0;
    rleRec.statelen = 0;
    rleRec.laststate = 0;
    rleInfo = &rleRec;
    myfread = rle_fread;
  } else {
    rleInfo = NULL;
    myfread = std_fread;
  }

  wbytes = width * pelbytes;

  if (vertrev) {
    start = 0;
    end = height;
    dir = 1;
  } else {
    /* We need to reverse loading order of rows. */
    start = height-1;
    end = -1;
    dir = -1;
  }

  for (i = start; i != end; i += dir) {
    data = pixels + i*wbytes;

    /* Suck in the data one row at a time. */
    if (myfread(rleInfo, data, pelbytes, width, fp) != width) {
      /* Probably premature end of file. */
      if (verbose) {
        printf ("TGA: error reading (ftell == %ld, width=%d)\n",
          ftell(fp), width);
      }
      return NULL;
    }  

    if (horzrev) {
      /* We need to mirror row horizontally. */
      for (j = 0; j < width/2; j++) {
        GLubyte tmp;

        for (k = 0; k < pelbytes; k++) {
          tmp = data[j*pelbytes+k];
          data[j*pelbytes+k] = data[(width-j-1)*pelbytes+k];
          data[(width-j-1)*pelbytes+k] = tmp;
        }
      }
    }
  }

  if (rle) {
    free(rleInfo->statebuf);
  }

  if (fgetc (fp) != EOF) {
    if (verbose) printf ("TGA: too much input data, ignoring extra...\n");
  }

  genericImage = (gliGenericImage*) malloc(sizeof(gliGenericImage));
  genericImage->width = width;
  genericImage->height = height;
  genericImage->format = format;
  genericImage->components = components;
  genericImage->cmapEntries = colors;
  genericImage->cmapFormat = GL_BGR_EXT;  // XXX fix me
  genericImage->cmap = cmap;
  genericImage->pixels = pixels;

  return genericImage;
}
Exemple #2
0
Mesh* Load3ds(string URL, Entity* parent_ent){
  int Size;
  //Local OldDir:String
  unsigned char Red, Green, Blue;
  //unsigned char Percent;
  //Local Pixmap:TPixmap
  Stream = File::ReadResourceFile(URL);
  if (Stream == 0) return 0;

  //Size = Stream.Size()
  fseek(Stream->pFile, 0, SEEK_END); // seek to end of file
  Size = ftell(Stream->pFile); // get current file pointer
  fseek(Stream->pFile, 0, SEEK_SET);

  // Read Main-Chunk
  ReadChunk();
  if (ChunkID != M3D_3DS_MAIN || ChunkSize != Size) {
    Stream->CloseFile();
    //Print "No 3DS File"
    return 0;
  }
  // Find 3DEditor-Chunk
  while (Stream->Eof()==0){
    ReadChunk();
    if (ChunkID == M3D_3DS_3DEDITOR){
      break;
    }else{
      SkipChunk();
    }
  }

  //OldDir = CurrentDir()
  //If String(URL) <> "" Then ChangeDir(ExtractDir(String(URL)))
  mesh = Mesh::CreateMesh();
  while (Stream->Eof()==0){
    ReadChunk();
    switch (ChunkID){
    case M3D_3DS_OBJECTBLOCK:
      ReadCString(); // ' ObjectName
      break;
    case M3D_3DS_BrushBLOCK:
      ReadBrushBlock();
      break;
    case M3D_3DS_TRIMESH:
      ReadTriMesh();
      break;
    case M3D_3DS_VERTEXLIST:
      ReadVertexList();
      break;
    case M3D_3DS_FACELIST:
      ReadFaceList();
      break;
    case M3D_3DS_FACEMATLIST:
      ReadFaceMatList();
      break;
    case M3D_3DS_TEXCOORDS:
      ReadTexCoords();
      break;
    case M3D_3DS_BrushNAME:
      //Loader.Brush = CreateBrush()
      brush->name = ReadCString();
      break;
    case M3D_3DS_BrushAMBIENT:
      //ReadChunk();
      //ReadRGB(ChunkID, Red, Green, Blue);
      //brush->SetAmbientColor(Red, Green, Blue);
      break;
    case M3D_3DS_BrushDIFFUSE:
      ReadChunk();
      ReadRGB(ChunkID, Red, Green, Blue);
      //brush->BrushColor(Red, Green, Blue);
      break;
    case M3D_3DS_BrushSPECULAR:
      //'Loader.ReadChunk()
      //'Loader.ReadRGB(Loader.ChunkID, Red, Green, Blue)
      //'Loader.Brush.SetSpecularColor(Red, Green, Blue)
      break;
    case M3D_3DS_BrushSHININESS:
      //'Loader.ReadChunk()
      //'Percent = Loader.ReadPercent(Loader.ChunkID)
      //'Loader.Brush.BrushShininess(Percent)
      break;
    case M3D_3DS_MAPFILENAME:
      LoadMap();
      if(brush->no_texs==0) brush->BrushColor(Red, Green, Blue); // only use rgb if no texture
      break;
    case M3D_3DS_MAPVSCALE:
      texture->v_scale = Stream->ReadFloat();
      break;
    case M3D_3DS_MAPUSCALE:
      texture->u_scale = Stream->ReadFloat();
      break;
    case M3D_3DS_MAPUOFFSET:
      texture->u_pos = Stream->ReadFloat();
      break;
    case M3D_3DS_MAPVOFFSET:
      texture->v_pos = Stream->ReadFloat();
      break;
    case M3D_3DS_MAPROTATION:
      texture->angle = Stream->ReadFloat();
      break;
    default:
      if ((ChunkID == M3D_3DS_TEXTUREMAP1) || (ChunkID == M3D_3DS_TEXTUREMAP2)) {
        ReadMap(ChunkID);
      }else{
        SkipChunk();
      }
    }
  }
  Stream->CloseFile();

  if (surface!=0){
    MovedTris.sort();
    int CheckSurface=0;
    for(list<int>::const_reverse_iterator it = MovedTris.rbegin(); it != MovedTris.rend(); it++){
      surface->RemoveTri(*it);
      CheckSurface=1;
    }
    MovedTris.clear();

    if (surface->no_tris==0 && CheckSurface !=0) {
      delete surface;
      mesh->surf_list.remove(surface);
      mesh->no_surfs=mesh->no_surfs-1;
    }
  }


//    ChangeDir(OldDir)
//    Loader.Surface.UpdateVertices()
//    Loader.Surface.UpdateTriangles()
  mesh->UpdateNormals();
  /*Loader.Mesh.UpdateBuffer()
  Print Loader.Surface.Tris.Length
  Print Loader.Surface.no_verts
  'Loader.Mesh.FlipMesh()*/

  mesh->class_name="Mesh";
  mesh->AddParent(parent_ent);
  Entity::entity_list.push_back(mesh);
  if(mesh->parent!=0){
    mesh->mat.Overwrite(mesh->parent->mat);
    mesh->UpdateMat();
  }else{
    mesh->UpdateMat(true);
  }
  return mesh;
}
Exemple #3
0
SQInteger sqstd_ftell(SQFILE file)
{
	return ftell((FILE *)file);
}
status_t GraphicBufferSource::submitBuffer_l(
        const BufferQueue::BufferItem &item, int cbi) {
    ALOGV("submitBuffer_l cbi=%d", cbi);

    int64_t timeUs = getTimestamp(item);
    if (timeUs < 0ll) {
        return UNKNOWN_ERROR;
    }

    CodecBuffer& codecBuffer(mCodecBuffers.editItemAt(cbi));
    codecBuffer.mGraphicBuffer = mBufferSlot[item.mBuf];
    codecBuffer.mBuf = item.mBuf;
    codecBuffer.mFrameNumber = item.mFrameNumber;

    OMX_BUFFERHEADERTYPE* header = codecBuffer.mHeader;

#ifdef MTK_AOSP_ENHANCEMENT
    //error handling ALPS01556865
    if( NULL == header->pBuffer )
    {
        ALOGW("WARNING: header->pBuffer is NULL, line:%d", __LINE__);
        return OMX_ErrorBadParameter;
    }
    else if(mDumpRawFile != NULL) //try to dump if necessary
    {
        OMX_U8 *rawbuffer=NULL;
        uint32_t mWidth;
        uint32_t mHeight;
        uint32_t mStride;

        buffer_handle_t _handle = *((buffer_handle_t*)(header->pBuffer + 4));
        //GraphicBufferMapper &gbm = GraphicBufferMapper::getInstance();
        codecBuffer.mGraphicBuffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, (void**)&rawbuffer);
        //gbm.lock(_handle, GRALLOC_USAGE_SW_READ_OFTEN, Rect(iSrcWidth, iSrcHeight), (void**)&rawbuffer);
        //memcpy(mEffectYUVBuffer, buffer, iSrcWidth*iSrcHeight*3/2);

        mWidth = codecBuffer.mGraphicBuffer->getWidth();
        mHeight = codecBuffer.mGraphicBuffer->getHeight();
        mStride = codecBuffer.mGraphicBuffer->getStride();
        
        ALOGD("getWidth:%d, Height:%d, Stride:%d, PixelFormat:%d", mWidth,
            mHeight, mStride,
            codecBuffer.mGraphicBuffer->getPixelFormat());

        if (NULL == rawbuffer)
        {
            codecBuffer.mGraphicBuffer->unlock();
        }
        else if ( ( 0 != codecBuffer.mGraphicBuffer->getWidth() ) && (mDumpRawFile != NULL) ) {
                size_t nWrite = fwrite(rawbuffer, 1, mWidth*mHeight*4,  mDumpRawFile);//fix ARGB, FIXME
                ALOGD("RawBuf %x, written %d bytes, %d, mRangeLength = %d, ftell = %d", 
                    rawbuffer, nWrite, mWidth*mHeight, mStride*mHeight, (int)ftell(mDumpRawFile));
        }
        if (NULL != rawbuffer)
        {
            codecBuffer.mGraphicBuffer->unlock();
        }
    }
#endif //ifdef MTK_AOSP_ENHANCEMENT

    CHECK(header->nAllocLen >= 4 + sizeof(buffer_handle_t));
    OMX_U8* data = header->pBuffer;
    buffer_handle_t handle;
    if (!mUseGraphicBufferInMeta) {
        const OMX_U32 type = kMetadataBufferTypeGrallocSource;
        handle = codecBuffer.mGraphicBuffer->handle;
        memcpy(data, &type, 4);
        memcpy(data + 4, &handle, sizeof(buffer_handle_t));
    } else {
        // codecBuffer holds a reference to the GraphicBuffer, so
        // it is valid while it is with the OMX component
        const OMX_U32 type = kMetadataBufferTypeGraphicBuffer;
        memcpy(data, &type, 4);
        // passing a non-reference-counted graphicBuffer
        GraphicBuffer *buffer = codecBuffer.mGraphicBuffer.get();
        handle = buffer->handle;
        memcpy(data + 4, &buffer, sizeof(buffer));
    }

    status_t err = mNodeInstance->emptyDirectBuffer(header, 0,
            4 + sizeof(buffer_handle_t), OMX_BUFFERFLAG_ENDOFFRAME,
            timeUs);
    if (err != OK) {
        ALOGW("WARNING: emptyDirectBuffer failed: 0x%x", err);
        codecBuffer.mGraphicBuffer = NULL;
        return err;
    }

    ALOGV("emptyDirectBuffer succeeded, h=%p p=%p bufhandle=%p",
            header, header->pBuffer, handle);
    return OK;
}
Exemple #5
0
CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data,
                              const char *pinnedpubkey,
                              const unsigned char *pubkey, size_t pubkeylen)
{
  FILE *fp;
  unsigned char *buf = NULL, *pem_ptr = NULL;
  long filesize;
  size_t size, pem_len;
  CURLcode pem_read;
  CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
#ifdef curlssl_sha256sum
  CURLcode encode;
  size_t encodedlen, pinkeylen;
  char *encoded, *pinkeycopy, *begin_pos, *end_pos;
  unsigned char *sha256sumdigest = NULL;
#endif

  /* if a path wasn't specified, don't pin */
  if(!pinnedpubkey)
    return CURLE_OK;
  if(!pubkey || !pubkeylen)
    return result;

  /* only do this if pinnedpubkey starts with "sha256//", length 8 */
  if(strncmp(pinnedpubkey, "sha256//", 8) == 0) {
#ifdef curlssl_sha256sum
    /* compute sha256sum of public key */
    sha256sumdigest = malloc(SHA256_DIGEST_LENGTH);
    if(!sha256sumdigest)
      return CURLE_OUT_OF_MEMORY;
    curlssl_sha256sum(pubkey, pubkeylen,
                      sha256sumdigest, SHA256_DIGEST_LENGTH);
    encode = Curl_base64_encode(data, (char *)sha256sumdigest,
                                SHA256_DIGEST_LENGTH, &encoded, &encodedlen);
    Curl_safefree(sha256sumdigest);

    if(encode)
      return encode;

    infof(data, "\t public key hash: sha256//%s\n", encoded);

    /* it starts with sha256//, copy so we can modify it */
    pinkeylen = strlen(pinnedpubkey) + 1;
    pinkeycopy = malloc(pinkeylen);
    if(!pinkeycopy) {
      Curl_safefree(encoded);
      return CURLE_OUT_OF_MEMORY;
    }
    memcpy(pinkeycopy, pinnedpubkey, pinkeylen);
    /* point begin_pos to the copy, and start extracting keys */
    begin_pos = pinkeycopy;
    do {
      end_pos = strstr(begin_pos, ";sha256//");
      /*
       * if there is an end_pos, null terminate,
       * otherwise it'll go to the end of the original string
       */
      if(end_pos)
        end_pos[0] = '\0';

      /* compare base64 sha256 digests, 8 is the length of "sha256//" */
      if(encodedlen == strlen(begin_pos + 8) &&
         !memcmp(encoded, begin_pos + 8, encodedlen)) {
        result = CURLE_OK;
        break;
      }

      /*
       * change back the null-terminator we changed earlier,
       * and look for next begin
       */
      if(end_pos) {
        end_pos[0] = ';';
        begin_pos = strstr(end_pos, "sha256//");
      }
    } while(end_pos && begin_pos);
    Curl_safefree(encoded);
    Curl_safefree(pinkeycopy);
#else
    /* without sha256 support, this cannot match */
    (void)data;
#endif
    return result;
  }

  fp = fopen(pinnedpubkey, "rb");
  if(!fp)
    return result;

  do {
    /* Determine the file's size */
    if(fseek(fp, 0, SEEK_END))
      break;
    filesize = ftell(fp);
    if(fseek(fp, 0, SEEK_SET))
      break;
    if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE)
      break;

    /*
     * if the size of our certificate is bigger than the file
     * size then it can't match
     */
    size = curlx_sotouz((curl_off_t) filesize);
    if(pubkeylen > size)
      break;

    /*
     * Allocate buffer for the pinned key
     * With 1 additional byte for null terminator in case of PEM key
     */
    buf = malloc(size + 1);
    if(!buf)
      break;

    /* Returns number of elements read, which should be 1 */
    if((int) fread(buf, size, 1, fp) != 1)
      break;

    /* If the sizes are the same, it can't be base64 encoded, must be der */
    if(pubkeylen == size) {
      if(!memcmp(pubkey, buf, pubkeylen))
        result = CURLE_OK;
      break;
    }

    /*
     * Otherwise we will assume it's PEM and try to decode it
     * after placing null terminator
     */
    buf[size] = '\0';
    pem_read = pubkey_pem_to_der((const char *)buf, &pem_ptr, &pem_len);
    /* if it wasn't read successfully, exit */
    if(pem_read)
      break;

    /*
     * if the size of our certificate doesn't match the size of
     * the decoded file, they can't be the same, otherwise compare
     */
    if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen))
      result = CURLE_OK;
  } while(0);

  Curl_safefree(buf);
  Curl_safefree(pem_ptr);
  fclose(fp);

  return result;
}
Exemple #6
0
static off_t custom_seek(void* io, off_t offset, int seek_type) {
	FILE* f = reinterpret_cast<FILE*>(io);
	fseek(f, offset, seek_type);
	return ftell(f);
}
Exemple #7
0
unsigned char pnd_emit_icon ( char *targetpath, pnd_disco_t *p ) {
  //#define BITLEN (8*1024)
#define BITLEN (64*1024)
  char buffer [ FILENAME_MAX ]; // target filename
  char from [ FILENAME_MAX ];   // source filename
  unsigned char bits [ BITLEN ];
  unsigned int bitlen;
  FILE *pnd, *target;

  // prelim .. if a pnd file, and no offset found, discovery code didn't locate icon.. so bail.
  if ( ( p -> object_type == pnd_object_type_pnd ) &&
       ( ! p -> pnd_icon_pos ) )
  {
    return ( 0 ); // discover code didn't find it, so FAIL
  }

  // determine filename for target
  sprintf ( buffer, "%s/%s.png", targetpath, p -> unique_id /*, p -> subapp_number*/ ); // target

  /* first.. open the source file, by type of application:
   * are we looking through a pnd file or a dir?
   */
  if ( p -> object_type == pnd_object_type_directory ) {
    sprintf ( from, "%s/%s", p -> object_path, p -> icon );
  } else if ( p -> object_type == pnd_object_type_pnd ) {
    sprintf ( from, "%s/%s", p -> object_path, p -> object_filename );
  }

  pnd = fopen ( from, "rb" );

  if ( ! pnd ) {
    pnd_log ( PND_LOG_DEFAULT, "    Emit icon, couldn't open source\n" );
    return ( 0 );
  }

  unsigned int len;

  target = fopen ( buffer, "wb" );

  if ( ! target ) {
    fclose ( pnd );
    pnd_log ( PND_LOG_DEFAULT, "    Emit icon, couldn't open target\n" );
    return ( 0 );
  }

  fseek ( pnd, 0, SEEK_END );
  len = ftell ( pnd );
  //fseek ( pnd, 0, SEEK_SET );

  fseek ( pnd, p -> pnd_icon_pos, SEEK_SET );

  len -= p -> pnd_icon_pos;

  pnd_log ( PND_LOG_DEFAULT, "    Emit icon, length: %u\n", len );

  while ( len ) {

    if ( len > (BITLEN) ) {
      bitlen = (BITLEN);
    } else {
      bitlen = len;
    }

    if ( fread ( bits, bitlen, 1, pnd ) != 1 ) {
      fclose ( pnd );
      fclose ( target );
      unlink ( buffer );
      pnd_log ( PND_LOG_DEFAULT, "    Emit icon, bad read\n" );
      return ( 0 );
    }

#if 0
    {
      unsigned int i = 0;
      char bigbuffer [ 200 * 1024 ] = "\0";
      char b [ 10 ];
      pnd_log ( PND_LOG_DEFAULT, "    Read hexdump\n" );
      while ( i < bitlen ) {
	sprintf ( b, "%x,", bits [ i ] );
	strcat ( bigbuffer, b );
	i++;
      }
      pnd_log ( PND_LOG_DEFAULT, bigbuffer );
    }
#endif

    if ( fwrite ( bits, bitlen, 1, target ) != 1 ) {
      fclose ( pnd );
      fclose ( target );
      unlink ( buffer );
      pnd_log ( PND_LOG_DEFAULT, "    Emit icon, bad write\n" );
      return ( 0 );
    }

    len -= bitlen;
    //pnd_log ( PND_LOG_DEFAULT, "    Emit icon, next block, length: %u\n", len );
  } // while

  fclose ( pnd );
  fclose ( target );

  //pnd_log ( PND_LOG_DEFAULT, "    Emit icon, done.\n" );

  return ( 1 );
}
Exemple #8
0
long File::tell() const
{
	return ftell(stream);
}
Exemple #9
0
int fontx_load(const char *path, fontx_t* fontx, int type, int wmargin, int hmargin, int bold)
{

	FILE *file = NULL;

	int ret = -1;
	long size = 0;

	fontx_hdr *fontx_header = NULL;

	if (!strcmp("rom0:KROM",path) || !strcmp("rom0:/KROM",path))
	{

		if (type == SINGLE_BYTE)
		{

			ret = fontx_load_single_krom(fontx);

		}
		else
		{

			ret = fontx_load_double_krom(fontx);

		}

		if (ret < 0)
		{

			printf("Error opening %s\n", path);
			return -1;

		}

	}

	else
	{

		file = fopen(path, "r");

		if (file == NULL)
		{

			printf("Error opening %s\n", path);
			return -1;

		}

		// get size of file
		fseek(file, 0, SEEK_END);
		size = ftell(file);
		fseek(file, 0, SEEK_SET);

		fontx->font = (char *)malloc(size);

		if (fontx->font == NULL)
		{

			printf("Error allocating %ld bytes of memory.\n", size);
			fclose(file);
			return -1;

		}

		fread(fontx->font, size, 1, file);

		fclose(file);

	}

	fontx_header = (fontx_hdr*)fontx->font;

	if (strncmp(fontx_header->id, "FONTX2", 6) != 0)
	{

		printf("Not FONTX2 type font!\n");
		free(fontx->font);

		return -1;

	}

	if (fontx_header->type != type)
	{

		printf("Type mismatch\n");
		free(fontx->font);

		return -1;

	}

	// Fill in some information about the font
	strcpy(fontx->name,fontx_header->name);

	fontx->rowsize = ((fontx_header->width+7)>>3);
	fontx->charsize = fontx->rowsize * fontx_header->height;
	fontx->w_margin = wmargin;
	fontx->h_margin = hmargin;
	fontx->bold = bold;

	// This is the offset that character data starts
	if (fontx_header->type == SINGLE_BYTE)
	{

		fontx->offset = 17;

	}
	else
	{

		// 17 + 1 + (number of tables * 4) bytes
		fontx->offset = 18 + (fontx_header->table_num * 4);

	}

	return 0;

}
Exemple #10
0
int main(int argc, char **argv) {
  if (argc != 4) {
    fprintf(stderr, "Usage: %s seqfile indexfile readfile\n", argv[0]);
    exit(-1);
  }
  char *seq, *seqfile, *indexfile, *readfile, *buf = malloc(256*256), *revbuf = malloc(256*256), c;
  fm_index *fmi;
  int len;
  int i, j, k, jj;
  FILE *sfp, *ifp, *rfp;
  seqfile = argv[1];
  indexfile = argv[2];
  readfile = argv[3];
  sfp = fopen(seqfile, "rb");
  if (sfp == 0) {
    fprintf(stderr, "Could not open sequence\n");
    exit(-1);
  }
  fseek(sfp, 0L, SEEK_END);
  len = ftell(sfp);
  rewind(sfp);
  seq = malloc(len/4+1);
  for (i = 0; i < len/4 + 1; ++i) {
    switch(fgetc(sfp)) {
    case 'C': c = 64; break;
    case 'G': c = 128; break;
    case 'T': c = 192; break;
    default: c = 0;
    }
    switch(fgetc(sfp)) {
    case 'C': c ^= 16; break;
    case 'G': c ^= 32; break;
    case 'T': c ^= 48;
    }
    switch(fgetc(sfp)) {
    case 'C': c ^= 4; break;
    case 'G': c ^= 8; break;
    case 'T': c ^= 12;
    }
    switch(fgetc(sfp)) {
    case 'C': c ^= 1; break;
    case 'G': c ^= 2; break;
    case 'T': c ^= 3;
    }
    seq[i] = c;
  }
  // Handle the last character (which is at seq[len/4]
  c = 0;
  for (i = 0; i < len&3; ++i) {
    switch(fgetc(sfp)) {
    case 'C': c ^= 64 >> (2 * i); break;
    case 'G': c ^= 128 >> (2 * i); break;
    case 'T': c ^= 192 >> (2 * i);
    }
    seq[len/4] = c;
  }
  fclose(sfp);
  
  // Open index file
  ifp = fopen(indexfile, "rb");
  if (ifp == 0) {
    fprintf(stderr, "Could not open index file");
    exit(-1);
  }
  fmi = read_index(seq, ifp);
  fclose(ifp);

  // And now we go read the index file
  rfp = fopen(readfile, "r");
  if (rfp == 0) {
    fprintf(stderr, "Could not open reads file");
    exit(-1);
  }
  // Read one line ("read") and try aligning it
  
  int naligned = 0;
  int nread = 0;
  while (!feof(rfp)) {
    // Align the read using mms and mms_mismatch (which is a sort of wrapper
    // for the correct calls to mms_continue)
    if (!fgets(buf, 256*256-1, rfp))
      break;
    nread++;
    if (buf[strlen(buf)-1] == '\n')
      buf[strlen(buf)-1] = 0;
    int len = strlen(buf);
    for (int i = 0; i < len; ++i) {
      // Replace with "compressed" characters
      switch(buf[i]) {
      case 'A':
	buf[i] = 0;
	revbuf[len-i-1] = 3;
	break;
      case 'C':
	buf[i] = 1;
	revbuf[len-i-1] = 2;
	break;
      case 'T':
	buf[i] = 3;
	revbuf[len-i-1] = 0;
	break;
      case 'G':
	buf[i] = 2;
	revbuf[len-i-1] = 1;
	break;
      default: // 'N'
	buf[i] = 5;
	revbuf[len-i-1] = 5;
	break;
      }
    }

    int aligned = 0;

    int score = 0;
    stack *s = stack_make();
    //    int thresh = (int) (-1.2 * (1+len));

    //    int pos = align_read(fmi, seq, buf, len, 10);
    int pos = align_read_anchored(fmi, seq, buf, len, 12, s);
    if (pos) {
      naligned++;
      printf("%d\n", pos + 1);
      stack_print_destroy(s);
    }
    else {
      stack_destroy(s);
      s = stack_make();
      //      pos = align_read(fmi, seq, revbuf, len, 10);
      pos = align_read_anchored(fmi, seq, revbuf, len, 12, s);
      if (pos) {
	naligned++;
	printf("%d\n", pos + 1);
	stack_print_destroy(s);
      }
      else {
	printf("0\n");
	stack_destroy(s);
      }
    }

    /*
    while(len) {
      if (score <= thresh) {
	break;
      }
      int start, end;
      int matched = mms(fmi, buf, len, &start, &end);
      if (matched < 10) {
      	len -= 1;
      	score -= 3;
      	continue;
      }
      // Try continuing from these results
      int res_len = len - matched;
      int tscore = score;
      while(res_len && tscore > thresh) {
	int penalty;
	int matched_cont = mms_mismatch(fmi, seq, buf, res_len, &start, &end, &penalty);
	//printf("%d\n", matched_cont);
	if (matched_cont == -1) {
	  tscore = thresh;
	  break; // too many matches
	}
	tscore += penalty;
	res_len -= matched_cont;
      }
      if (tscore <= thresh) {
	len -= 1;
	score -= 3;
	continue;
      }
      else {
	// we're good
	printf("%d\n", unc_sa(fmi, start) + 1);
	aligned = 1;
	naligned++;
	break;
      }
    }

    if (!aligned) {
      // Try aligning as a reverse complement
      int score = 0;
      while(len) {
	if (score <= thresh) {
	  printf("0\n");
	  break;
	}
	int start, end;
	int matched = mms(fmi, revbuf, len, &start, &end);
	//	printf("Matched %d\n", matched);
	if (matched < 10) {
	  len -= 1;
	  score -= 3;
	  continue;
	}
	// Try continuing from these results
	int res_len = len - matched;
	int tscore = score;
	while(res_len && tscore > thresh) {
	  int penalty;
	  int matched_cont = mms_mismatch(fmi, seq, revbuf, res_len, &start, &end, &penalty);
	  //printf("%d\n", matched_cont);
	  if (matched_cont == -1) {
	    tscore = thresh;
	    break; // too many matches
	  }
	  tscore += penalty;
	  res_len -= matched_cont;
	}
	if (tscore <= thresh) {
	  len -= 1;
	  score -= 3;
	  continue;
	}
	else {
	  // we're good
	  printf("%d\n", unc_sa(fmi, start) + 1);
	  naligned++;
	  break;
	}
      }
    }
    */
  }
  fclose(rfp);
  fprintf(stderr, "%d of %d reads aligned\n", naligned, nread);
  
  free(buf);
  free(revbuf);
  destroy_fmi(fmi);
  free(seq);
  return 0;
}
	//! retrieves the file size of the open file
	void getFileSize()
	{
		fseek(File, 0, SEEK_END);
		Size = ftell(File);
		fseek(File, 0, SEEK_SET);
	}
//----------------------------------------------------------------
CPUTResult CPUTConfigFileA::LoadFile(const std::string &szFilename)
{
    int nBytes = 0;
    char *pFileContents = NULL;
#if 1 
#ifdef UNICODE
    CPUTResult result = CPUTFileSystem::ReadFileContentsA(szFilename, (UINT *)&nBytes, (void **)&pFileContents, true);
#else
    CPUTResult result = CPUTFileSystem::ReadFileContents(szFilename, (UINT *)&nBytes, (void **)&pFileContents, true);
#endif
    if(CPUTFAILED(result))
    {
		DEBUG_PRINT(_L("Failed to read file %s"), szFilename.c_str());
		return result;
    }
    
#else
    // Load the file
    FILE               *pFile = NULL;
    CPUTResult result = CPUTFileSystem::OpenFile(szFilename, &pFile);
    if(CPUTFAILED(result))
    {
        return result;
    }

//  _locale_t locale = _get_current_locale();

    /* Determine file size */
    fseek(pFile, 0, SEEK_END);
    int nBytes = ftell(pFile); // for text files, this is an overestimate
    fseek(pFile, 0, SEEK_SET);

    /* Read the whole thing */
    char *pFileContents = new char[nBytes + 1];
    nBytes = (int)fread(pFileContents, 1, nBytes, pFile);
    fclose(pFile);
    
    pFileContents[nBytes] = 0; // add 0-terminator
#endif
    CPUTConfigBlockA   *pCurrBlock = NULL;
    int                 nCurrBlock = 0;
    
    /* Count the number of blocks */
    const char *pCur = pFileContents;
    const char *pStart, *pEnd;
    
    while(ReadLine(&pStart, &pEnd, &pCur))
    {
        const char *pOpen = FindFirst(pStart, pEnd, '[');
        const char *pClose = FindLast(pOpen + 1, pEnd, ']');
        if (pOpen < pClose)
        {
            // This line is a valid block header
            mnBlockCount++;
        }
    }
    
    // For files that don't have any blocks, just add the entire file to one block
    if(mnBlockCount == 0)
    {
        mnBlockCount   = 1;
    }
    
    pCur = pFileContents;
    mpBlocks = new CPUTConfigBlockA[mnBlockCount];
    pCurrBlock = mpBlocks;
    
    /* Find the first block first */
    while(ReadLine(&pStart, &pEnd, &pCur))
    {
        const char *pOpen = FindFirst(pStart, pEnd, '[');
        const char *pClose = FindLast(pOpen + 1, pEnd, ']');
        if (pOpen < pClose)
        {
            // This line is a valid block header
            pCurrBlock = mpBlocks + nCurrBlock++;
            //AssignStr(pCurrBlock->mszName, pOpen + 1, pClose, locale);
            pCurrBlock->mszName.assign(pOpen + 1, pClose);
            std::transform(pCurrBlock->mszName.begin(), pCurrBlock->mszName.end(), pCurrBlock->mszName.begin(), tolow);
        }
        else if (pStart < pEnd)
        {
            // It's a value
            if (pCurrBlock == NULL)
            {
                continue;
            }
            
            const char *pEquals = FindFirst(pStart, pEnd, '=');
            if (pEquals == pEnd)
            {
                // No value, just a key, save it anyway
                // Optimistically, we assume it's new
                std::string &name = pCurrBlock->mpValues[pCurrBlock->mnValueCount].szName;
                //AssignStr(name, pStart, pEnd, locale);
                name.assign(pStart, pEnd);
                
                bool dup = false;
                for(int ii=0;ii<pCurrBlock->mnValueCount;++ii)
                {
                    if(!pCurrBlock->mpValues[ii].szName.compare(name))
                    {
                        dup = true;
                        break;
                    }
                }
                if(!dup)
                {
                    pCurrBlock->mnValueCount++;
                }
            }
            else
            {
                const char *pNameStart = pStart;
                const char *pNameEnd = pEquals;
                const char *pValStart = pEquals + 1;
                const char *pValEnd = pEnd;
                
                RemoveWhitespace(pNameStart, pNameEnd);
                RemoveWhitespace(pValStart, pValEnd);
                
                // Optimistically assume the name is new
                std::string &name = pCurrBlock->mpValues[pCurrBlock->mnValueCount].szName;
                //AssignStr(name, pNameStart, pNameEnd, locale);
                name.assign(pNameStart, pNameEnd);
                std::transform(name.begin(), name.end(), name.begin(), tolow);
                
                bool dup = false;
                for(int ii=0;ii<pCurrBlock->mnValueCount;++ii)
                {
                    if(!pCurrBlock->mpValues[ii].szName.compare(name))
                    {
                        dup = true;
                        break;
                    }
                }
                if(!dup)
                {
                    //                    AssignStr(pCurrBlock->mpValues[pCurrBlock->mnValueCount].szValue, pValStart, pValEnd, locale);
                    pCurrBlock->mpValues[pCurrBlock->mnValueCount].szValue.assign(pValStart, pValEnd);
                    pCurrBlock->mnValueCount++;
                }
            }
        }
    }
    
    delete[] pFileContents;
    return CPUT_SUCCESS;
}
Exemple #13
0
WAVERESULT CWaves::ParseFile(const char *szFilename, LPWAVEFILEINFO pWaveInfo)
{
	WAVEFILEHEADER	waveFileHeader;
	RIFFCHUNK		riffChunk;
	WAVEFMT			waveFmt;
	WAVERESULT		wr = WR_BADWAVEFILE;

	if (!szFilename || !pWaveInfo)
		return WR_INVALIDPARAM;

	memset(pWaveInfo, 0, sizeof(WAVEFILEINFO));

	// Open the wave file for reading
	pWaveInfo->pFile = fopen(szFilename, "rb");
	if (pWaveInfo->pFile)
	{
		// Read Wave file header
		fread(&waveFileHeader, 1, sizeof(WAVEFILEHEADER), pWaveInfo->pFile);
		if (!_strnicmp(waveFileHeader.szRIFF, "RIFF", 4) && !_strnicmp(waveFileHeader.szWAVE, "WAVE", 4))
		{
			while (fread(&riffChunk, 1, sizeof(RIFFCHUNK), pWaveInfo->pFile) == sizeof(RIFFCHUNK))
			{
				if (!_strnicmp(riffChunk.szChunkName, "fmt ", 4))
				{
					if (riffChunk.ulChunkSize <= sizeof(WAVEFMT))
					{
						fread(&waveFmt, 1, riffChunk.ulChunkSize, pWaveInfo->pFile);

						// Determine if this is a WAVEFORMATEX or WAVEFORMATEXTENSIBLE wave file
						if (waveFmt.usFormatTag == WAVE_FORMAT_PCM)
						{
							pWaveInfo->wfType = WF_EX;
							memcpy(&pWaveInfo->wfEXT.Format, &waveFmt, sizeof(PCMWAVEFORMAT));
						}
						else if (waveFmt.usFormatTag == WAVE_FORMAT_EXTENSIBLE)
						{
							pWaveInfo->wfType = WF_EXT;
							memcpy(&pWaveInfo->wfEXT, &waveFmt, sizeof(WAVEFORMATEXTENSIBLE));
						}
					}
					else
					{
						fseek(pWaveInfo->pFile, riffChunk.ulChunkSize, SEEK_CUR);
					}
				}
				else if (!_strnicmp(riffChunk.szChunkName, "data", 4))
				{
					pWaveInfo->ulDataSize = riffChunk.ulChunkSize;
					pWaveInfo->ulDataOffset = ftell(pWaveInfo->pFile);
					fseek(pWaveInfo->pFile, riffChunk.ulChunkSize, SEEK_CUR);
				}
				else
				{
					fseek(pWaveInfo->pFile, riffChunk.ulChunkSize, SEEK_CUR);
				}

				// Ensure that we are correctly aligned for next chunk
				if (riffChunk.ulChunkSize & 1)
					fseek(pWaveInfo->pFile, 1, SEEK_CUR);
			}

			if (pWaveInfo->ulDataSize && pWaveInfo->ulDataOffset && ((pWaveInfo->wfType == WF_EX) || (pWaveInfo->wfType == WF_EXT)))
				wr = WR_OK;
			else
				fclose(pWaveInfo->pFile);
		}
	}
	else
	{
		wr = WR_INVALIDFILENAME;
	}

	return wr;
}
Exemple #14
0
/**
 * Group:
 *     C
 *
 * Function:
 *     Gua_Status System_SourceFunctionWrapper(void *nspace, Gua_Short argc, Gua_Object *argv, Gua_Object *object, Gua_String error)
 *
 * Description:
 *     Source function wrapper.
 *
 * Arguments:
 *     nspace,    a pointer to a structure Gua_Namespace. Must do a cast before use it;
 *     argc,      the number of arguments to pass to the function;
 *     argv,      an array containing the arguments to the function;
 *                argv[0] is the function name;
 *     object,    a structure containing the return object of the function;
 *     error,     a pointer to the error message.
 *
 * Results:
 *     Read a script file and try to execute it.
 */
Gua_Status System_SourceFunctionWrapper(void *nspace, Gua_Short argc, Gua_Object *argv, Gua_Object *object, Gua_String error)
{
    Gua_Namespace *top;
    FILE *fp;
    Gua_String script;
    Gua_String p;
    Gua_Integer length;
    Gua_Short status;
    Gua_Object argv1;
    Gua_String expression;
    Gua_String errMessage;
    
    top = (Gua_Namespace *)nspace;
    while (top->previous) {
        top = (Gua_Namespace *)top->previous;
    }
    
    if (argc == 0) {
        errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
        sprintf(errMessage, "%s\n", "no function specified");
        strcat(error, errMessage);
        Gua_Free(errMessage);
        
        return GUA_ERROR;
    }
    
    if (argc != 2) {
        errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
        sprintf(errMessage, "%s %-.20s...\n", "wrong number of arguments for function", Gua_ObjectToString(argv[0]));
        strcat(error, errMessage);
        Gua_Free(errMessage);
        
        return GUA_ERROR;
    }
    
    if (Gua_ObjectType(argv[1]) != OBJECT_TYPE_STRING) {
        errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
        sprintf(errMessage, "%s %-.20s...\n", "illegal argument 1 for function", Gua_ObjectToString(argv[0]));
        strcat(error, errMessage);
        Gua_Free(errMessage);
        
        return GUA_ERROR;
    }
    
    fp = fopen(Gua_ObjectToString(argv[1]), "r");
    
    if (fp == NULL) {
        errMessage = (Gua_String) Gua_Alloc(sizeof(char) * MAX_ERROR_MSG_SIZE + 1);
        sprintf(errMessage, "%s %-.20s...\n", "can not open file", Gua_ObjectToString(argv[1]));
        strcat(error, errMessage);
        Gua_Free(errMessage);
        
        return GUA_ERROR;
    }
    
    fseek(fp, 0, SEEK_END);
    length = ftell(fp) + 1;
    fseek(fp, 0, SEEK_SET);
    
    script = (char *)Gua_Alloc(sizeof(char) * length + 1);
    memset(script, '\0', length + 1);
    
    expression = (char *)Gua_Alloc(sizeof(char) * EXPRESSION_SIZE + 1);
    memset(expression, '\0', EXPRESSION_SIZE + 1);
    
    status = GUA_OK;
    
    if (length > 0) {
        /* Store the main script argv[1]. */
        strcpy(expression, "$argv[1]");
        p = expression;
        p = Gua_Expression(top, p, &argv1, &status, error);

        /* Set the new argv[1]. */
        sprintf(expression, "$argv[1] = \"%s\"", Gua_ObjectToString(argv[1]));
        p = expression;
        p = Gua_Expression(top, p, object, &status, error);
        if (!Gua_IsPObjectStored(object)) {
            Gua_FreeObject(object);
        }
        
        /* Load the script. */
        fread(script, sizeof(char), length, fp);
        p = script;
        p = Gua_Evaluate(top, p, object, &status, error);
        
        /* Restore the main script argv[1]. */
        sprintf(expression, "$argv[1] = \"%s\"", Gua_ObjectToString(argv1));
        if (!Gua_IsObjectStored(argv1)) {
            Gua_FreeObject(&argv1);
        }
        p = expression;
        p = Gua_Expression(top, p, &argv1, &status, error);
        if (!Gua_IsObjectStored(argv1)) {
            Gua_FreeObject(&argv1);
        }
    }
    
    fclose(fp);
    
    Gua_Free(expression);
    Gua_Free(script);
    
    if (status != GUA_OK) {
        return GUA_ERROR;
    }
    
    return GUA_OK;
}
Exemple #15
0
bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding )
{
	if ( !file ) 
	{
		SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	// Delete the existing data:
	Clear();
	location.Clear();

	// Get the file size, so we can pre-allocate the string. HUGE speed impact.
	long length = 0;
	fseek( file, 0, SEEK_END );
	length = ftell( file );
	fseek( file, 0, SEEK_SET );

	// Strange case, but good to handle up front.
	if ( length <= 0 )
	{
		SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	// If we have a file, assume it is all one big XML file, and read it in.
	// The document parser may decide the document ends sooner than the entire file, however.
	TIXML_STRING data;
	data.reserve( length );

	// Subtle bug here. TinyXml did use fgets. But from the XML spec:
	// 2.11 End-of-Line Handling
	// <snip>
	// <quote>
	// ...the XML processor MUST behave as if it normalized all line breaks in external 
	// parsed entities (including the document entity) on input, before parsing, by translating 
	// both the two-character sequence #xD #xA and any #xD that is not followed by #xA to 
	// a single #xA character.
	// </quote>
	//
	// It is not clear fgets does that, and certainly isn't clear it works cross platform. 
	// Generally, you expect fgets to translate from the convention of the OS to the c/unix
	// convention, and not work generally.

	/*
	while( fgets( buf, sizeof(buf), file ) )
	{
		data += buf;
	}
	*/

	char* buf = new char[ length+1 ];
	buf[0] = 0;

	if ( fread( buf, length, 1, file ) != 1 ) {
		delete [] buf;
		SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	const char* lastPos = buf;
	const char* p = buf;

	buf[length] = 0;
	while( *p ) {
		assert( p < (buf+length) );
		if ( *p == 0xa ) {
			// Newline character. No special rules for this. Append all the characters
			// since the last string, and include the newline.
			data.append( lastPos, (p-lastPos+1) );	// append, include the newline
			++p;									// move past the newline
			lastPos = p;							// and point to the new buffer (may be 0)
			assert( p <= (buf+length) );
		}
		else if ( *p == 0xd ) {
			// Carriage return. Append what we have so far, then
			// handle moving forward in the buffer.
			if ( (p-lastPos) > 0 ) {
				data.append( lastPos, p-lastPos );	// do not add the CR
			}
			data += (char)0xa;						// a proper newline

			if ( *(p+1) == 0xa ) {
				// Carriage return - new line sequence
				p += 2;
				lastPos = p;
				assert( p <= (buf+length) );
			}
			else {
				// it was followed by something else...that is presumably characters again.
				++p;
				lastPos = p;
				assert( p <= (buf+length) );
			}
		}
		else {
			++p;
		}
	}
	// Handle any left over characters.
	if ( p-lastPos ) {
		data.append( lastPos, p-lastPos );
	}		
	delete [] buf;
	buf = 0;

	Parse( data.c_str(), 0, encoding );

	if (  Error() )
        return false;
    else
		return true;
}
wav_file *wav_open(const char *filename, int sample_rate, int channels)
{
	wav_file *wav;
	UINT32 bps, temp32;
	UINT16 align, temp16;

	/* allocate memory for the wav struct */
	wav = (wav_file *) malloc(sizeof(struct _wav_file));
	if (!wav)
		return NULL;

	/* create the file */
	wav->file = fopen(filename, "wb");
	if (!wav->file)
	{
		free(wav);
		return NULL;
	}

	/* write the 'RIFF' header */
	fwrite("RIFF", 1, 4, wav->file);

	/* write the total size */
	temp32 = 0;
	wav->total_offs = ftell(wav->file);
	fwrite(&temp32, 1, 4, wav->file);

	/* write the 'WAVE' type */
	fwrite("WAVE", 1, 4, wav->file);

	/* write the 'fmt ' tag */
	fwrite("fmt ", 1, 4, wav->file);

	/* write the format length */
	temp32 = intel_long(16);
	fwrite(&temp32, 1, 4, wav->file);

	/* write the format (PCM) */
	temp16 = intel_short(1);
	fwrite(&temp16, 1, 2, wav->file);

	/* write the channels */
	temp16 = intel_short(channels);
	fwrite(&temp16, 1, 2, wav->file);

	/* write the sample rate */
	temp32 = intel_long(sample_rate);
	fwrite(&temp32, 1, 4, wav->file);

	/* write the bytes/second */
	bps = sample_rate * 2 * channels;
	temp32 = intel_long(bps);
	fwrite(&temp32, 1, 4, wav->file);

	/* write the block align */
	align = 2 * channels;
	temp16 = intel_short(align);
	fwrite(&temp16, 1, 2, wav->file);

	/* write the bits/sample */
	temp16 = intel_short(16);
	fwrite(&temp16, 1, 2, wav->file);

	/* write the 'data' tag */
	fwrite("data", 1, 4, wav->file);

	/* write the data length */
	temp32 = 0;
	wav->data_offs = ftell(wav->file);
	fwrite(&temp32, 1, 4, wav->file);

	return wav;
}
Exemple #17
0
GLuint Model_PLY::LoadFlat(GLchar* filename)
{
	char* pch = strstr(filename, ".ply");

	if (pch != nullptr)
	{
		// Open file and read it.
		FILE* file;
		fopen_s(&file, filename, "rb");

		fseek(file, 0, SEEK_END);
		long fileSize = ftell(file); //ftell is get the current position of pointer.

		try
		{
			vertexBuffer = (float*)malloc(fileSize);
		}
		catch (char*) // but why should be char* here?
		{
			return -1;
		}

		if (vertexBuffer == nullptr)
		{
			return -1;
		}

		fseek(file, 0, SEEK_SET);

		faceTriangles = (float*)malloc(fileSize * sizeof(float));
		verticesNormals = (float*)malloc(fileSize * sizeof(float));

		if (file != nullptr)
		{
			int i = 0;
			int temp = 0;
			int normalIndex = 0;
			int triangleIndex = 0;
			char buffer[1000]; // every time gets 1000 buffer.

			fgets(buffer, 300, file); //ply

			// READ HEADER
			//-------------------

			// Find number of vertexes
			// e.g. element vertex 12
			while (strncmp("element vertex", buffer, strlen("element vertex")) != 0)
			{
				fgets(buffer, 300, file);
			}
			strcpy_s(buffer, sizeof(buffer) - strlen("element vertex"), buffer + strlen("element vertex")); //erase "element vertex" header.
			sscanf_s(buffer, "%i", &this->numConnectedPoints); //read integer value for num of points.
			std::cout << "Number of connected point is : " << numConnectedPoints << std::endl;

			// find number of faces
			// e.g. element face 10
			fseek(file, 0, SEEK_SET);
			while (strncmp("element face", buffer, strlen("element face")) != 0)
			{
				fgets(buffer, 300, file);
			}
			strcpy_s(buffer, sizeof(buffer) - strlen("element face"), buffer + strlen("element face")); //erase "element face" header.
			sscanf_s(buffer, "%i", &this->numFaces); //read integer value for num of faces.
			std::cout << "Number of faces is : " << numFaces << std::endl;

			// go to end_header
			while (strncmp(("end_header"), buffer, strlen("end_header")) != 0)
			{
				fgets(buffer, 300, file);
			}


			// Read vertexes
			i = 0;
			for (GLuint iter = 0; iter < this->numConnectedPoints; ++iter)
			{
				fgets(buffer, 300, file);

				sscanf_s(buffer, "%f %f %f", &vertexBuffer[i], &vertexBuffer[i + 1], &vertexBuffer[i + 2]);
				i += 3;
			}

			// Read faces
			i = 0;
			for (GLuint iter = 0; iter < this->numFaces; ++iter)
			{
				fgets(buffer, 300, file);

				if ('3' == buffer[0])
				{
					int vert0 = 0, vert1 = 0, vert2 = 0;
					buffer[0] = ' ';
					sscanf_s(buffer, "%i%i%i", &vert0, &vert1, &vert2);




					// set values to faceTriangles.
 					faceTriangles[triangleIndex] = vertexBuffer[3 * vert0];
 					faceTriangles[triangleIndex + 1] = vertexBuffer[3 * vert0 + 1];
					faceTriangles[triangleIndex + 2] = vertexBuffer[3 * vert0 + 2];
 					faceTriangles[triangleIndex + 3] = vertexBuffer[3 * vert1];
					faceTriangles[triangleIndex + 4] = vertexBuffer[3 * vert1 + 1];
					faceTriangles[triangleIndex + 5] = vertexBuffer[3 * vert1 + 2];
 					faceTriangles[triangleIndex + 6] = vertexBuffer[3 * vert2];
					faceTriangles[triangleIndex + 7] = vertexBuffer[3 * vert2 + 1];
					faceTriangles[triangleIndex + 8] = vertexBuffer[3 * vert2 + 2];
 
 					// going to calculate verticesNormals.
					vec3 point0(vertexBuffer[3 * vert0], vertexBuffer[3 * vert0 + 1], vertexBuffer[3 * vert0 + 2]);
					vec3 point1(vertexBuffer[3 * vert1], vertexBuffer[3 * vert1 + 1], vertexBuffer[3 * vert1 + 2]);
					vec3 point2(vertexBuffer[3 * vert2], vertexBuffer[3 * vert2 + 1], vertexBuffer[3 * vert2 + 2]);
 
 					vec3 norm(0.0f);
 					this->calculateNormal(point0, point1, point2, norm);

 					for (int offset = 0; offset < 9; ++offset)
 					{
						verticesNormals[normalIndex + offset] = norm[offset % 3]; //set normal for each point.
 					}
 
 					normalIndex += 9; //set offset to next triangle. 

					triangleIndex += 9; //set offset to next triangle.
					numConnectedTriangles += 3; // three points per triangle
				}
				i += 3;
			}

			fclose(file);

		}
		else
		{
			std::cerr << "Error : Can not open file." << std::endl;
		}
	}
	else
	{
		std::cerr << "Error : File do not have a \".ply\" extension." << std::endl;
	}
	return 0;
}
	////////////////////////////////////
	// Texture::ImageTGA::Load
	void Texture::ImageTGA::Load(const char* filename)
	{
		int				columns, rows, numPixels;
		unsigned char	*pixbuf;
		int				row, column;
		unsigned char	*buf_p;
		unsigned char	*buffer;
		int				length;
		TargaHeader		targaHeader;
		unsigned char	*targa_rgba;
		unsigned char	tmp[2];
		FILE			*fp;

		// output
		int				width;
		int				height;

		DGL::LogPrint("Loading TGA Image '%s'...",filename);
        
		//
		// load the file
		//
		fp = fopen(filename, "rb");
		if(!fp)
			throw Daher::Exception("File Not Found");
		
		fseek(fp, 0, SEEK_END);
		length = ftell(fp);
		fseek(fp, 0, SEEK_SET);
		try {
			buffer = new unsigned char[length];
		} catch (std::bad_alloc) {
			throw Daher::Exception("Cannot allocate memory for TGA texture");
		}

		int result = fread(buffer, length, 1, fp);
		fclose(fp);

		buf_p = buffer;
		targaHeader.idLength = *buf_p++;
		targaHeader.colormapType = *buf_p++;
		targaHeader.imageType = *buf_p++;

		tmp[0] = buf_p[0];
		tmp[1] = buf_p[1];
		targaHeader.colormapIndex = MAKEWORD( tmp[0], tmp[1] );
		buf_p+=2;
		tmp[0] = buf_p[0];
		tmp[1] = buf_p[1];
		targaHeader.colormapLength = MAKEWORD( tmp[0], tmp[1] );
		buf_p+=2;
		targaHeader.colormapSize = *buf_p++;
		targaHeader.xOrigin = MAKEWORD( buf_p[0], buf_p[1] );
		buf_p+=2;
		targaHeader.yOrigin = MAKEWORD( buf_p[0], buf_p[1] );
		buf_p+=2;
		targaHeader.width = MAKEWORD( buf_p[0], buf_p[1] );
		buf_p+=2;
		targaHeader.height = MAKEWORD( buf_p[0], buf_p[1] );
		buf_p+=2;
		targaHeader.pixelSize = *buf_p++;
		targaHeader.attributes = *buf_p++;

		if (targaHeader.imageType!=2 
			&& targaHeader.imageType!=10) 
			throw Daher::Exception("Only type 2 and 10 targa RGB images supported");

		if (targaHeader.colormapType !=0 
			|| (targaHeader.pixelSize!=32 && targaHeader.pixelSize!=24))
			throw Daher::Exception("Only 32 or 24 bit images supported (no colormaps)");

		columns = targaHeader.width;
		rows = targaHeader.height;
		numPixels = columns * rows;

		width = columns;
		height = rows;

		this->data = new unsigned char[numPixels*4];
		targa_rgba = this->data;

		if (targaHeader.idLength != 0)
			buf_p += targaHeader.idLength;  // skip TARGA image comment

		if (targaHeader.imageType==2) {  // Uncompressed, RGB images
			for(row=0; row< rows;  row++) {
				pixbuf = targa_rgba + row*columns*4;
				for(column=0; column<columns; column++) {
					unsigned char red,green,blue,alphabyte;
					switch (targaHeader.pixelSize) {
						case 24:
                            blue = *buf_p++;
							green = *buf_p++;
							red = *buf_p++;
							*pixbuf++ = red;
							*pixbuf++ = green;
							*pixbuf++ = blue;
							*pixbuf++ = 255;
							break;
						case 32:
							blue = *buf_p++;
							green = *buf_p++;
							red = *buf_p++;
							alphabyte = *buf_p++;
							*pixbuf++ = red;
							*pixbuf++ = green;
							*pixbuf++ = blue;
							*pixbuf++ = alphabyte;
							break;
					}
				}
			}
		}
		else if (targaHeader.imageType==10) {   // Runlength encoded RGB images (RLE)
			unsigned char red,green,blue,alphabyte,packetHeader,packetSize,j;
			for(row=0; row<rows; row++) {
				pixbuf = targa_rgba + row*columns*4;
				for(column=0; column<columns; ) {
					packetHeader= *buf_p++;
					packetSize = 1 + (packetHeader & 0x7f);
					if (packetHeader & 0x80) {        // run-length packet
						switch (targaHeader.pixelSize) {
							case 24:
								blue = *buf_p++;
								green = *buf_p++;
								red = *buf_p++;
								alphabyte = 255;
								break;
							case 32:
								blue = *buf_p++;
								green = *buf_p++;
								red = *buf_p++;
								alphabyte = *buf_p++;
								break;
						}
						for(j=0;j<packetSize;j++) {
							*pixbuf++=red;
							*pixbuf++=green;
							*pixbuf++=blue;
							*pixbuf++=alphabyte;
							column++;
							if (column==columns) { // run spans across rows
								column=0;
								if (row<rows)
									row++;
								else
									goto breakOut;
								pixbuf = targa_rgba + row*columns*4;
							}
						}
					} else {                            // non run-length packet
						for(j=0;j<packetSize;j++) {
							switch (targaHeader.pixelSize) {
								case 24:
									blue = *buf_p++;
									green = *buf_p++;
									red = *buf_p++;
									*pixbuf++ = red;
									*pixbuf++ = green;
									*pixbuf++ = blue;
									*pixbuf++ = 255;
									break;
								case 32:
									blue = *buf_p++;
									green = *buf_p++;
									red = *buf_p++;
									alphabyte = *buf_p++;
									*pixbuf++ = red;
									*pixbuf++ = green;
									*pixbuf++ = blue;
									*pixbuf++ = alphabyte;
									break;
							}
							column++;
							if (column==columns) { // pixel packet run spans across rows
								column=0;
								if (row<rows)
									row++;
								else
									goto breakOut;
								pixbuf = targa_rgba + row*columns*4;
							}						
						}
					}
				}
breakOut:;
			}
		}
		delete [] buffer;

		this->components	= 4;
		this->width			= width;
		this->height		= height;
		this->format		= GL_RGBA;
	}
Exemple #19
0
static void ProcFileModRef( FILE *fp )
/************************************/
{
    byte        hdr[ 3 ];
    unsigned_16 page_len;
    unsigned_32 offset;
    char        *module_name;

    page_len = 0;
    RecBuff = NULL;
    RecMaxLen = 0;
    module_name = NULL;
    for(;;) {
        offset = ftell( fp );
        if( fread( hdr, 1, 3, fp ) != 3 )
            break;
        RecLen = hdr[ 1 ] | ( hdr[ 2 ] << 8 );
        ResizeBuff( RecLen );
        RecPtr = RecBuff;
        if( fread( RecBuff, RecLen, 1, fp ) == 0 )
            break;
        RecLen--;
        isMS386 = hdr[ 0 ] & 1;
        switch( hdr[ 0 ] & ~1 ) {
        case CMD_THEADR:
            if( module_name != NULL )
                free( module_name );
            GetName();
            *RecPtr = 0;
            module_name = malloc( strlen( (char *)NamePtr ) + 1 );
            strcpy( module_name, (char *)NamePtr );
            break;
        case CMD_MODEND:
            if( module_name != NULL )
                free( module_name );
            module_name = NULL;
            if( page_len != 0 ) {
                offset = ftell( fp );
                offset = page_len - offset % page_len;
                if( offset != page_len ) {
                    fseek( fp, offset, SEEK_CUR );
                }
            }
            break;
        case CMD_PUBDEF:
            if( ( GetIndex() | GetIndex() ) == 0 )
                GetUInt();
            while( ! EndRec() ) {
                GetName();
                *RecPtr = 0;
                if( SymbolExists( pubdef_tab, (char *)NamePtr ) != 0 ) {
                    if( SymbolExists( extdef_tab, module_name ) == 0 ) {
                        AddSymbol( extdef_tab, module_name, NULL );
                        printf( "%s\n", module_name );
                    }
                }
                GetOffset();
                GetIndex();
            }
            break;
        case LIB_HEADER_REC:
            if( isMS386 ) {
                fseek( fp, 0L, SEEK_END );
                page_len = 0;
            } else {
                page_len = RecLen + 4;
            }
            break;
        default:
            break;
        }
    }
    free( RecBuff );
}
int _tmain(int argc, _TCHAR* argv[])
{
	lzo_bytep in;
	lzo_bytep out;
	lzo_voidp wrkmem;
	lzo_uint in_len;
	lzo_uint out_len;
	lzo_uint new_len;

//lzo 초기화
	if (lzo_init() != LZO_E_OK)
	{
		printf("lzo_init() failed\n");
		return 0;
	}

//파일 로딩
	FILE* fp = 0;
	errno_t err = fopen_s(&fp, "LICENSE", "rb");
	if (err != 0)
		return 0;

	fseek(fp, 0L, SEEK_END);
	in_len = ftell(fp);

	fseek(fp, 0L, SEEK_SET);

//메모리 할당
//작은 데이터를 압축할 경우 데이터의 크기가 오히려 증가할 경우가 있기 때문에
//압축된 결과를 저장하는 버퍼는 원본 버퍼보다 조금 크게 잡는다.
	in = (lzo_bytep)xmalloc(in_len);
	out_len = in_len + in_len / 16 + 64 + 3;
	out = (lzo_bytep)xmalloc(out_len);
	wrkmem = (lzo_voidp)xmalloc(LZO1X_1_MEM_COMPRESS);
	if (in == NULL || out == NULL || wrkmem == NULL)
	{
		printf("out of memory\n");
		return 0;
	}

//데이터를 읽어 들인다.
	fread(in, in_len, 1, fp);
	fclose(fp);

//데이터 압축
	int r = lzo1x_1_compress(in, in_len, out, &out_len, wrkmem);
	if (r == LZO_E_OK)
		printf("compressed %lu bytes into %lu bytes\n",
		(unsigned long)in_len, (unsigned long)out_len);
	else
	{
		/* this should NEVER happen */
		printf("internal error - compression failed: %d\n", r);
		return 2;
	}
	/* check for an incompressible block */
	if (out_len >= in_len)
	{
		printf("This block contains incompressible data.\n");
		return 0;
	}

//압축 해제
	new_len = in_len;
	r = lzo1x_decompress(out, out_len, in, &new_len, NULL);
	if (r == LZO_E_OK && new_len == in_len)
		printf("decompressed %lu bytes back into %lu bytes\n",
		(unsigned long)out_len, (unsigned long)in_len);
	else
	{
		/* this should NEVER happen */
		printf("internal error - decompression failed: %d\n", r);
		return 1;
	}

	lzo_free(wrkmem);
	lzo_free(out);
	lzo_free(in);
	printf("Simple compression test passed.\n");

	return 0;
}
Exemple #21
0
unsigned char *pnd_emit_icon_to_buffer ( pnd_disco_t *p, unsigned int *r_buflen ) {
  // this is shamefully mostly a copy of emit_icon() above; really, need to refactor that to use this routine
  // with a fwrite at the end...
  char from [ FILENAME_MAX ];   // source filename
  char bits [ 8 * 1024 ];
  unsigned int bitlen;
  FILE *pnd = NULL;
  unsigned char *target = NULL, *targiter = NULL;

  // prelim .. if a pnd file, and no offset found, discovery code didn't locate icon.. so bail.
  if ( ( p -> object_type == pnd_object_type_pnd ) &&
       ( ! p -> pnd_icon_pos ) )
  {
    return ( NULL ); // discover code didn't find it, so FAIL
  }

  /* first.. open the source file, by type of application:
   * are we looking through a pnd file or a dir?
   */
  if ( p -> object_type == pnd_object_type_directory ) {
    sprintf ( from, "%s/%s", p -> object_path, p -> icon );
  } else if ( p -> object_type == pnd_object_type_pnd ) {
    sprintf ( from, "%s/%s", p -> object_path, p -> object_filename );
  }

  pnd = fopen ( from, "r" );

  if ( ! pnd ) {
    return ( NULL );
  }

  // determine length of file, then adjust by icon position to find begin of icon
  unsigned int len;

  fseek ( pnd, 0, SEEK_END );
  len = ftell ( pnd );
  //fseek ( pnd, 0, SEEK_SET );

  fseek ( pnd, p -> pnd_icon_pos, SEEK_SET );

  len -= p -> pnd_icon_pos;

  // create target buffer
  target = malloc ( len );

  if ( ! target ) {
    fclose ( pnd );
    return ( 0 );
  }

  targiter = target;

  if ( r_buflen ) {
    *r_buflen = len;
  }

  // copy over icon to target
  while ( len ) {

    if ( len > (8*1024) ) {
      bitlen = (8*1024);
    } else {
      bitlen = len;
    }

    if ( fread ( bits, bitlen, 1, pnd ) != 1 ) {
      fclose ( pnd );
      free ( target );
      return ( NULL );
    }

    memmove ( targiter, bits, bitlen );
    targiter += bitlen;

    len -= bitlen;
  } // while

  fclose ( pnd );

  return ( target );
}
Exemple #22
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
/*
int main(int __argc, char** __argv)
*/
{
	int retval = 0;

	setlocale( LC_ALL, "Japanese" );

	if (__argc > 2) {
		Message("[usage]");
		Message("  afxtail.exe [file]");
		Message("  ※引数を省略した場合は既存のtailを終了する。");
		return -1;
	}
	if (__argc == 1) {
		HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, TRUE, __AFXTAIL_EVENT__);
		if (hEvent != INVALID_HANDLE_VALUE) {
			SetEvent(hEvent);
			CloseHandle(hEvent);
		}
		return 0;
	}

	HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, __AFXTAIL_EVENT__);

	char path[MAX_PATH];
	char dir[MAX_PATH];
	strcpy(path, __argv[1]);
	if (path[1] == ':') {
		strcpy(dir, __argv[1]);
		char* en = strrchr(dir, '\\');
		if (en == NULL) {
			Message("illegal parameter (%s)", __argv[1]);
			retval = -1;
			goto END;
		}
		*(en+1) = '\0';
	} else {
		DWORD size = sizeof(dir);
		if (::GetCurrentDirectory(size, dir) == FALSE) {
			Message("GetCurrentDirectory error(%d)", GetLastError());
			retval = -1;
			goto END;
		}
	}

	AfxInit(pAfxApp);

	HANDLE hNotif;
	FILE* fp = NULL;
	int cur = 0;
	int last = 0;
	bool first = true;
	char line[MAX_LINE_SIZE];
	while (1) {
		fp = _fsopen(path, "r", _SH_DENYNO);
		if (fp == NULL) {
			Message("Can not open file (%s)", path);
			break;
		}
		fseek(fp, 0, SEEK_END);
        last = ftell(fp);
		if (first) {
			first = false;
			cur = last - MAX_LINE_SIZE * 10;
			if (cur < 0) cur = 0;
			hNotif = FindFirstChangeNotification(dir, TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE);
			int hist[6] = { -1, -1, -1, -1, -1, -1 };
			fseek(fp, cur, SEEK_SET);
			while (fgets(line, sizeof(line)-1, fp) != NULL) {
				hist[5] = hist[4];
				hist[4] = hist[3];
				hist[3] = hist[2];
				hist[2] = hist[1];
				hist[1] = hist[0];
				hist[0] = ftell(fp);
			}
			for (int idx=5; idx>=0; idx--) {
				if (hist[idx] >= 0) {
					cur = hist[idx];
					break;
				}
			}
			Message("-- afxtail start --");
		}
		if (last > cur) {
			fseek(fp, cur, SEEK_SET);
		} else if (cur > last) {
			fseek(fp, 0, SEEK_SET);
		}
		if (last != cur) {
			int adjust = 0;
			while (fgets(line, sizeof(line)-1, fp) != NULL) {
				char* ln = strchr(line, '\r');
				if (ln == NULL) {
					ln = strchr(line, '\n');
				}
				if (ln == NULL) {
					if (strlen(line) < MAX_LINE_SIZE-1) {
						adjust = strlen(line);
						break;
					}
				} else {
					*ln = '\0';
				}
				Message("%s%s", _prefix, line);
			}
			cur = last - adjust;
		}
		fclose(fp);

		if (hNotif == INVALID_HANDLE_VALUE) {
			Sleep(5000);
		} else {
			while (WaitForSingleObject(hNotif, 1000) != WAIT_OBJECT_0) {
				if (WaitForSingleObject(hEvent, 0) == WAIT_OBJECT_0) {
					SetEvent(hEvent);
					Message("-- afxtail end(%s) --", path);
					goto END;
				}
			}
			if (!FindNextChangeNotification(hNotif)) {
				break;
			}
		}
	}

END:
	if (hEvent != INVALID_HANDLE_VALUE) {
		CloseHandle(hEvent);
	}

	AfxCleanup(pAfxApp);

	return retval;
}
Exemple #23
0
int main(int argc, char **argv)
{
	FILE *infile = NULL;
	FILE *outfile = NULL;
	unsigned char *buffer = NULL;
	unsigned char *keybuf = key;
	int len=0, i=0, keynum=0, method=0;
	
	if(argc<3)
	{
		printf("usage: %s infile outfile (optional: keynum(1, 2, 3))\n",argv[0]);
		return 0;
	}
	
	infile = fopen(argv[1],"rb");
	
	if(!infile)
	{
		printf("Could not open %s\n",argv[1]);
		return -1;
	}
	
	if(argc==4)
	{
		keynum = atoi(argv[3])-1;
		
		if(keynum<0 || keynum>2)
		{
			printf("Invalid key, range is 1-3\n");
			return -2;
		}
	}
	
	fseek(infile,0,SEEK_END);
	len = ftell(infile);
	rewind(infile);
	
	buffer = (unsigned char*)calloc(len,sizeof(unsigned char));
	
	if(buffer==NULL)
	{
		printf("Could not allocate %d bytes for the buffer\n",len);
		return -3;
	}
	
	fread(buffer,1,len,infile);
	
	/*
		Encryption:
		
		00404A27   33C9             XOR ECX,ECX
		00404A29   8BC1             MOV EAX,ECX
		00404A2B   99               CDQ
		00404A2C   F7FB             IDIV EBX
		00404A2E   8A0439           MOV AL,BYTE PTR DS:[ECX+EDI]
		00404A31   8A92 D4B25B00    MOV DL,BYTE PTR DS:[EDX+5BB2D4]
		00404A37   02D1             ADD DL,CL
		00404A39   2AC2             SUB AL,DL
		00404A3B   880439           MOV BYTE PTR DS:[ECX+EDI],AL
		00404A3E   41               INC ECX
		00404A3F   81F9 00A0DA00    CMP ECX,AIKAEN.00DAA000
		00404A45  ^7C E2            JL SHORT AIKAEN.00404A29
	*/
	
	if(argc!=4) /* key search */
	{
		int found=0, x=0;
		
		printf("Attempting to determine which key to use for decryption...\n");
		
		for(x=0; x<3; x++)
		{
			found = 1;
			
			for(i=0; i<0x10; i++)
			{
				if(buffer[i] - (keybuf[i%keylen[x]] + i) != 0)
				{
					found = 0;
					break;
				}
			}
		
			if(found==1)
			{
				printf("Key %d seems likely. If the results are incorrect then you can manually set the key by passing the key number as an argument.\n",x);
				
				keynum = x;
				break;
			}
				
			keybuf += keylen[x];
		}
		
		if(found==0)
		{
			printf("It seems like none of the keys worked. This could possibly be a new encryption key or an incorrect file.\nHere's a hex dump of the first 0x40 bytes to help you determine which it is:\n\n");
		
			for(i=0; i<0x40; i+=0x10)
			{
				printf("%08x\t",i);
				
				for(x=i; x<i+0x10; x++)
					printf("%02x ",buffer[x]);
					
				printf("\n");
			}
			
			if(buffer[0]==0 && buffer[1]==1 && buffer[2]==2 && buffer[3]==3)
			{
				method = 1;
				printf("\nDetected as possibly not using a key\n");
			}
			else if(buffer[0]==0 && buffer[1]==0 && buffer[2]==0 && buffer[3]==0)
			{
				printf("\nThis doesn't look like an encrypted file, exiting...");
				return -5;
			}
			else
			{
				printf("\nDefaulting to key 1...\n");
				keynum = 0;
			}
			//return -4;
		}
	}
	else
	{
		for(i=0; i<keynum; i++)
			keybuf += keylen[i];
	}
	
	for(i=0; i<len; i++)
	{
			buffer[i] -= i%5;
	}
	
	outfile = fopen(argv[2],"wb");
	fwrite(buffer,1,len,outfile);
	
	free(buffer);
	fclose(infile);
	fclose(outfile);
	
	return 0;
}
/*
 * Reads the lines from the fiven \"input\" file and creates the reads and prefixes
 * for the read filter.  The \"read_filter\" given is allocated.
 *
 * Returns 0 on success.  Errors cause the usage message and exit. 
 */
int read_filter_from_file(FILE *input, read_filter_t *read_filter)
{
    int   isNewline;              /* Boolean indicating we've read a CR or LF */
    long  lFileLen;               /* Length of file */
    long  lIndex;                 /* Index into cThisLine array */
    long  lLineCount;             /* Current line number */
    long  lLineLen;               /* Current line length */
    long  lStartPos;              /* Offset of start of current line */
    long  lTotalChars;            /* Total characters read */
    char  cThisLine[MAX_REC_LEN]; /* Contents of current line */
    char *cFile;                  /* Dynamically allocated buffer (entire file) */
    char *cThisPtr;               /* Pointer to current position in cFile */

    char *filter_type = NULL;
    char *prefix;
    char *read;

    fseek(input, 0L, SEEK_END);  /* Position to end of file */
    lFileLen = ftell(input);     /* Get file length */
    rewind(input);               /* Back to start of file */

    cFile = calloc(lFileLen + 1, sizeof(char));

    if(cFile == NULL )
	{
	    fprintf(stderr, "\nInsufficient memory to read file.\n");
	    return -1;
	}

    /* Read the entire file into cFile */
    if (1 != fread(cFile, lFileLen, 1, input))
	return -1;

    lLineCount  = 0L;
    lTotalChars = 0L;

    cThisPtr    = cFile;              /* Point to beginning of array */

    while (*cThisPtr)                 /* Read until reaching null char */
	{
	    lIndex    = 0L;                 /* Reset counters and flags */
	    isNewline = 0;
	    lStartPos = lTotalChars;

	    while (*cThisPtr)               /* Read until reaching null char */
		{
		    if (!isNewline)               /* Haven't read a CR or LF yet */
			{
			    if (*cThisPtr == CR || *cThisPtr == LF) /* This char IS a CR or LF */
				isNewline = 1;                        /* Set flag */
			}

		    else if (*cThisPtr != CR && *cThisPtr != LF) /* Already found CR or LF */
			break;                                     /* Done with line */

		    /* Don't copy LS or CR */
		    if (*cThisPtr != CR && *cThisPtr != LF) {
			cThisLine[lIndex++] = *cThisPtr++; /* Add char to output and increment */
			++lTotalChars;
		    } else {
			cThisPtr++;
		    }

		} /* end while (*cThisPtr) */

	    cThisLine[lIndex] = '\0';     /* Terminate the string */
	    ++lLineCount;                 /* Increment the line counter */
	    lLineLen = strlen(cThisLine); /* Get length of line */

	    /* Find the one and only = in the string. */
	    if(strchr(cThisLine,'=') != NULL && (strchr(cThisLine,'=') == strrchr(cThisLine,'='))) {
		filter_type = strtok (cThisLine, "=");
	    } else {
		fprintf(stderr, "Baddly formatted read filter \"%s\".  Expected an \"=\" character in middle of filter.\n", cThisLine);
		usage(1);
	    }

	    if (!strcmp(filter_type, "prefix")) {
		prefix = strtok (NULL, "=");
		if(prefix == NULL) {
		    fprintf(stderr, "Bad prefix \"%s\" in read filter \"%s\".\n", prefix, cThisLine);
		    usage(1);
		} else {
		    ++(read_filter->prefixes_size);
		    read_filter->prefixes = (char**) realloc (read_filter->prefixes, read_filter->prefixes_size * sizeof(char *));
		    read_filter->prefixes[read_filter->prefixes_size - 1] =  (char*) calloc (strlen(prefix) + 1,sizeof(char));
		    strcpy(read_filter->prefixes[read_filter->prefixes_size - 1], prefix);
		}
	    } else if (!strcmp(filter_type, "read")) {
		read = strtok (NULL, "=");
		if(read == NULL) {
		    fprintf(stderr, "Bad read \"%s\" in read filter \"%s\".\n", read, cThisLine);
		    usage(1);
		} else {
		    ++(read_filter->reads_size);
		    read_filter->reads = (char**) realloc (read_filter->reads, read_filter->reads_size * sizeof(char *));
		    read_filter->reads[read_filter->reads_size - 1] =  (char*) calloc (strlen(read) + 1,sizeof(char));
		    strcpy(read_filter->reads[read_filter->reads_size - 1], read);
		}
	    } else {
		fprintf(stderr, "Unrecognized filter type \"%s\" given as part of read filter \"%s\".  The valid filter types are \"%s\".\n", filter_type, cThisLine, "prefix or read");
		usage(1);
	    }

	}

    free(cFile);
    return 0;
}
void* CALL HGE_Impl::Resource_Load(const char *filename, DWORD *size)
{
	static char *res_err="Can't load resource: %s";

	CResourceList *resItem=res;
	char szName[_MAX_PATH];
	char szZipName[_MAX_PATH];
	unzFile zip;
	unz_file_info file_info;
	int done, i;
	void *ptr;
	//HANDLE hF;
	FILE *file;

	if(filename[0]=='\\' || filename[0]=='/' || filename[1]==':') goto _fromfile; // skip absolute paths

	// Load from pack
 
	strcpy(szName,filename);
	SDL_strupr(szName);
	for(i=0; szName[i]; i++) { if(szName[i]=='/') szName[i]='\\'; }

	while(resItem)
	{
		zip=unzOpen(resItem->filename);
		done=unzGoToFirstFile(zip);
		while(done==UNZ_OK)
		{
			unzGetCurrentFileInfo(zip, &file_info, szZipName, sizeof(szZipName), NULL, 0, NULL, 0);
			SDL_strupr(szZipName);
			for(i=0; szZipName[i]; i++)	{ if(szZipName[i]=='/') szZipName[i]='\\'; }
			if(!strcmp(szName,szZipName))
			{
				if(unzOpenCurrentFilePassword(zip, resItem->password[0] ? resItem->password : 0) != UNZ_OK)
				{
					unzClose(zip);
					sprintf(szName, res_err, filename);
					_PostError(szName);
					return 0;
				}

				ptr = malloc(file_info.uncompressed_size);
				if(!ptr)
				{
					unzCloseCurrentFile(zip);
					unzClose(zip);
					sprintf(szName, res_err, filename);
					_PostError(szName);
					return 0;
				}

				if(unzReadCurrentFile(zip, ptr, file_info.uncompressed_size) < 0)
				{
					unzCloseCurrentFile(zip);
					unzClose(zip);
					free(ptr);
					sprintf(szName, res_err, filename);
					_PostError(szName);
					return 0;
				}
				unzCloseCurrentFile(zip);
				unzClose(zip);
				if(size) *size=file_info.uncompressed_size;
				return ptr;
			}
			
			done=unzGoToNextFile(zip);
		}
		
		unzClose(zip);
		resItem=resItem->next;
	}

	// Load from file
_fromfile:

	/*hF = CreateFile(Resource_MakePath(filename), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, NULL);
	if(hF == INVALID_HANDLE_VALUE)
	{
		sprintf(szName, res_err, filename);
		_PostError(szName);
		return 0;
	}*/
	file = fopen(Resource_MakePath(filename), "rb");
	// if cannot open file
	if (!file){
		sprintf(szName, res_err, filename);
		_PostError(szName);
		return 0;
	}
	//file_info.uncompressed_size = GetFileSize(hF, NULL);
	fseek(file, 0, SEEK_END);
	file_info.uncompressed_size = ftell(file);
	fseek(file, 0, SEEK_SET);
	ptr = malloc(file_info.uncompressed_size);
	if(!ptr)
	{
		//CloseHandle(hF);
		fclose(file);
		sprintf(szName, res_err, filename);
		_PostError(szName);
		return 0;
	}
	int tmp = fread(ptr, file_info.uncompressed_size, 1, file);
	if (tmp <= 0)
	{
		fclose(file);
		free(ptr);
		sprintf(szName, res_err, filename);
		_PostError(szName);
		return 0;
	}
	
	//CloseHandle(hF);
	fclose(file);
	if(size) *size=file_info.uncompressed_size;
	return ptr;
}
Exemple #26
0
/*****************************************************************************
 * GRIB2Split() --
 *
 * Arthur Taylor / MDL
 *
 * PURPOSE
 *   Splits a file into its component GRIB messages (doesn't break up
 * subgrids).
 *
 * ARGUMENTS
 * filename = File to split. (Input)
 *   msgNum = Which message to look for (0 all, value otherwise). (Input)
 *   curMsg = Number of messages we've already looked at.
 *            In the procedured is the current message we are on. (Input)
 *
 * FILES/DATABASES:
 *    Opens a GRIB2 file for reading given its filename.
 *
 * RETURNS: int
 * +# = number of GRIB2 messages in the file.
 * -1 = Problems opening file for read.
 *
 * HISTORY
 *   5/2010 Arthur Taylor (MDL): Created.
 *
 * NOTES
 *****************************************************************************
 */
int GRIB2Split (char *filename, int msgNum, int curMsg)
{
   int grib_limit;      /* How many bytes to look for before the first "GRIB"
                         * in the file.  If not found, is not a GRIB file. */
   FILE *fp;            /* The opened GRIB2 file. */
   sInt4 offset = 0;    /* Where we are in the file. */
   char *ptr;           /* used to find the file extension. */
   char *buff;          /* Holds the info between records. */
   uInt4 buffLen;       /* Length of info between records. */
   int c;               /* Determine if end of the file without fileLen. */
   sInt4 sect0[SECT0LEN_WORD]; /* Holds the current Section 0. */
   uInt4 gribLen;       /* Length of the current GRIB message. */
   int version;         /* Which version of GRIB is in this message. */
   char *msg;           /* Used to pop messages off the error Stack. */
   sInt4 fileLen;       /* Length of the GRIB2 file. */
   char *outName = NULL; /* Name of the output file. */
   FILE *op;            /* The opened output file. */
   int i;               /* loop counter while writing bytes to output file. */

   grib_limit = GRIB_LIMIT;
   if (filename != NULL) {
      if ((fp = fopen (filename, "rb")) == NULL) {
         errSprintf ("ERROR: Problems opening %s for read.", filename);
         return -1;
      }
      ptr = strrchr (filename, '.');
      if (ptr != NULL) {
         if (strcmp (ptr, ".tar") == 0) {
            grib_limit = 5000;
         }
      }
      outName = (char *) malloc (strlen (filename) + 1 + 11);
   } else {
      fp = stdin;
      outName = (char *) malloc (strlen ("split.grb") + 1 + 11);
   }

   buff = NULL;
   buffLen = 0;
   while ((c = fgetc (fp)) != EOF) {
      ungetc (c, fp);
      /* curMsg++ done first so any error messages range from 1..n, instead
       * of 0.. n-1. Note curMsg should end up as n not (n-1) */
      curMsg++;
      /* Allow  2nd, 3rd, etc messages to have no limit to finding "GRIB". */
      if (curMsg > 1) {
         grib_limit = -1;
      }
      /* Read in the wmo header and sect0. */
      if (ReadSECT0 (fp, &buff, &buffLen, grib_limit, sect0, &gribLen,
                     &version) < 0) {
         if (curMsg == 1) {
            /* Handle case where we couldn't find 'GRIB' in the message. */
            preErrSprintf ("Inside GRIB2Split, Message # %d\n", curMsg);

            free (buff);
            free (outName);
            fclose (fp);
            return -2;
         } else {
            /* Handle case where there are trailing bytes. */
            msg = errSprintf (NULL);
            printf ("Warning: Inside GRIB2Split, Message # %d\n",
                    curMsg);
            printf ("%s", msg);
            free (msg);
            /* find out how big the file is. */
            fseek (fp, 0L, SEEK_END);
            fileLen = ftell (fp);
            /* fseek (fp, 0L, SEEK_SET); */
            printf ("There were %ld trailing bytes in the file.\n",
                    fileLen - offset);
            curMsg --;

            free (buff);
            free (outName);
            fclose (fp);
            return curMsg;
         }
      }

      if (version == -1) {
         /* TDLPack uses 4 bytes for FORTRAN record size, then another 8
          * bytes for the size of the record (so FORTRAN can see it), then
          * the data rounded up to an 8 byte boundary, then a trailing 4
          * bytes for a final FORTRAN record size.  However it only stores
          * in_ the gribLen the non-rounded amount, so we need to take care
          * of the rounding, and the trailing 4 bytes here. */
         gribLen = ((sInt4) ceil (gribLen / 8.0)) * 8 + 4;
      }

      /* Write to file from buffLen to buffLen + gribLen bytes. */
      if ((msgNum == 0) || (curMsg == msgNum)) {
         if (filename != NULL) {
            sprintf (outName, "%s.%d", filename, curMsg);
         } else {
            sprintf (outName, "split.grb.%d", curMsg);
         }
         if ((op = fopen (outName, "wb")) == NULL) {
            errSprintf ("ERROR: Problems opening %s for write.", outName);

            free (buff);
            free (outName);
            fclose (fp);
            return -1;
         }
         fseek (fp, offset + buffLen, SEEK_SET);
         for (i = 0; i < gribLen; i++) {
            if ((c = getc(fp)) == EOF) {
               errSprintf ("ERROR: Reached end of file too soon?");

               free (buff);
               free (outName);
               fclose (fp);
               return -1;
            }
            putc (c, op);
         }
         fclose (op);
      }

      /* Continue on to the next GRIB2 message. */
      offset += buffLen + gribLen;
      fseek (fp, offset, SEEK_SET);
   }

   free (buff);
   free (outName);
   fclose (fp);
   return curMsg;
}
Memory *Memory::open(char *filename, unsigned char relative_path)
{
#if 1
    char fname[MAX_PATH] = {""};
    
    if (relative_path) {
        get_file_path( getenv( "FILESYSTEM" ), fname );
        strcat(fname, filename);
    }
    else {
        strcpy(fname, filename);
    }
    
    ifstream file;
    file.open(fname, ios::binary);
    
    if (!file.good()) {
        cout << "error opening file, " << fname << endl;
        return NULL;
    }
    
    Memory *memory = new Memory();
    
    strcpy(memory->filename, fname);
    
    unsigned int begin = (unsigned int)file.tellg();
    file.seekg(0, ios::end);
    unsigned int end = (unsigned int)file.tellg();
    file.seekg(0, ios::beg);
    memory->size = end - begin;
    
    memory->buffer = (unsigned char *)calloc(1, memory->size + 1);
    
    file.read((char *)memory->buffer, memory->size);
    file.close();
    
    return memory;
#else
    char fname[MAX_PATH] = {""};
    
    if (relative_path) {
        get_file_path( getenv( "FILESYSTEM" ), fname );
        strcat(fname, filename);
    }
    else {
        strcpy(fname, filename);
    }
    
    FILE *f = fopen(fname, "rb");
    
    if (!f) {
        return NULL;
    }
    
    Memory *memory = new Memory();
    
    strcpy(memory->filename, fname);
    
    fseek(f, 0, SEEK_END);
    memory->size = (unsigned int)ftell(f);
    fseek(f, 0, SEEK_SET);
    
    memory->buffer = (unsigned char *)calloc(1, memory->size + 1);
    fread(memory->buffer, memory->size, 1, f);
    memory->buffer[memory->size] = 0;
    
    fclose(f);
    
    return memory;
    
#endif
}
Exemple #28
0
sth_stash* initFont(GLPrimitiveRenderer* primRenderer)
{
	GLint err;

		struct sth_stash* stash = 0;
			OpenGL2RenderCallbacks* renderCallbacks = new OpenGL2RenderCallbacks(primRenderer);

	stash = sth_create(512,512,renderCallbacks);//256,256);//,1024);//512,512);
    err = glGetError();
    assert(err==GL_NO_ERROR);
    
	if (!stash)
	{
		fprintf(stderr, "Could not create stash.\n");
		return 0;
	}


#ifdef LOAD_FONTS_FROM_FILE
		int datasize;
	unsigned char* data;
	float sx,sy,dx,dy,lh;
	GLuint texture;

	

	const char* fontPaths[]={
	"./",
	"../../bin/",
	"../bin/",
	"bin/"
	};

	int numPaths=sizeof(fontPaths)/sizeof(char*);
	
	// Load the first truetype font from memory (just because we can).
    
	FILE* fp = 0;
	const char* fontPath ="./";
	char fullFontFileName[1024];

	for (int i=0;i<numPaths;i++)
	{
		
		fontPath = fontPaths[i];
		//sprintf(fullFontFileName,"%s%s",fontPath,"OpenSans.ttf");//"DroidSerif-Regular.ttf");
		sprintf(fullFontFileName,"%s%s",fontPath,"DroidSerif-Regular.ttf");//OpenSans.ttf");//"DroidSerif-Regular.ttf");
		fp = fopen(fullFontFileName, "rb");
		if (fp)
			break;
	}

    err = glGetError();
    assert(err==GL_NO_ERROR);
    
    assert(fp);
    if (fp)
    {
        fseek(fp, 0, SEEK_END);
        datasize = (int)ftell(fp);
        fseek(fp, 0, SEEK_SET);
        data = (unsigned char*)malloc(datasize);
        if (data == NULL)
        {
            assert(0);
            return 0;
        }
        else
            fread(data, 1, datasize, fp);
        fclose(fp);
        fp = 0;
    }

	if (!(droidRegular = sth_add_font_from_memory(stash, data)))
    {
        assert(0);
        return 0;
    }
    err = glGetError();
    assert(err==GL_NO_ERROR);

	// Load the remaining truetype fonts directly.
    sprintf(fullFontFileName,"%s%s",fontPath,"DroidSerif-Italic.ttf");

	if (!(droidItalic = sth_add_font(stash,fullFontFileName)))
	{
        assert(0);
        return 0;
    }
     sprintf(fullFontFileName,"%s%s",fontPath,"DroidSerif-Bold.ttf");

	if (!(droidBold = sth_add_font(stash,fullFontFileName)))
	{
        assert(0);
        return 0;
    }
    err = glGetError();
    assert(err==GL_NO_ERROR);
    
     sprintf(fullFontFileName,"%s%s",fontPath,"DroidSansJapanese.ttf");
    if (!(droidJapanese = sth_add_font(stash,fullFontFileName)))
	{
        assert(0);
        return 0;
    }
#else
	char* data2 = OpenSansData;
	unsigned char* data = (unsigned char*) data2;
	if (!(droidRegular = sth_add_font_from_memory(stash, data)))
	{
		printf("error!\n");
	}

#endif

	err = glGetError();
    assert(err==GL_NO_ERROR);

	return stash;
}
Exemple #29
0
int main()
{
  // Reading

  FILE *file = fopen("somefile.binary", "rb");
  assert(file);

  fseek(file, 0, SEEK_END);
  int size = ftell(file);
  rewind (file);
  printf("size: %d\n", size);

  char *buffer = (char*) malloc (sizeof(char)*size);
  assert(buffer);

  size_t read = fread(buffer, 1, size, file);
  assert(read == size);

  printf("data: %d", buffer[0]);
  for (int i = 1; i < size; i++)
    printf(",%d", buffer[i]);
  printf("\n");

  fclose (file);
  free (buffer);

  // Do it again, with a loop on feof

  printf("loop: ");
  file = fopen("somefile.binary", "rb");
  assert(file);
  while (!feof(file)) {
    char c = fgetc(file);
    if (c != EOF) printf("%d ", c);
  }
  fclose (file);
  printf("\n");

  // Standard streams

  printf("input:%s\n", gets((char*)malloc(1024)));
  fwrite("texto\n", 1, 6, stdout);
  fwrite("texte\n", 1, 6, stderr);
  putchar('$');
  putc('\n', stdout);

  // Writing

  char data[5] = { 10, 30, 20, 11, 88 };
  FILE *outf = fopen("go.out", "wb");
  fwrite(data, 1, 5, outf);
  fclose(outf);

  FILE *devNull = fopen("/dev/null", "rb");
  assert(devNull);

  char data2[10];
  FILE *inf = fopen("go.out", "rb");
  int num = fread(data2, 1, 10, inf);
  fclose(inf);
  printf("%d : %d,%d,%d,%d,%d\n", num, data2[0], data2[1], data2[2], data2[3], data2[4]);

  // Test reading a file that has not been cached
  
  FILE *other = fopen("test.file", "r");
  assert(other);

  char otherData[1000];
  num = fread(otherData, 1, 9, other);
  otherData[num] = 0;
  printf("other=%s.\n", otherData);

  // Seeking

  fseek(other, 2, SEEK_SET);
  num = fread(otherData, 1, 5, other);
  otherData[num] = 0;
  printf("seeked=%s.\n", otherData);

  fseek(other, -1, SEEK_CUR);
  num = fread(otherData, 1, 3, other);
  otherData[num] = 0;
  printf("seeked=%s.\n", otherData);

  fseek(other, -2, SEEK_END);
  num = fread(otherData, 1, 2, other);
  otherData[num] = 0;
  printf("seeked=%s.\n", otherData);

  fclose(other);

  // fscanf

  outf = fopen("fscan.f", "w");
  fprintf(outf, "10 hello");
  fclose(outf);

  int number;
  char text[100];
  inf = fopen("fscan.f", "r");
  num = fscanf(inf, "%d %s", &number, text);
  fclose(inf);
  printf("fscanfed: %d - %s\n", number, text);

  // temp files
  const char *tname = "file_XXXXXX.txt";
  char tname1[100];
  char tname2[100];
  strcpy(tname1, tname);
  strcpy(tname2, tname);
  assert(!strcmp(tname1, tname2)); // equal
  int f1 = mkstemp(tname1);
  int f2 = mkstemp(tname2);
  assert(f1 != f2);
  //printf("%d,%d,%s,%s\n", f1, f2, tname1, tname2);
  assert(strcmp(tname1, tname2)); // not equal
  assert(fopen(tname1, "r"));
  assert(fopen(tname2, "r"));
  assert(!fopen(tname2+1, "r")); // sanity check that we can't open just anything

  {
    FILE* f = tmpfile();
    assert(f);
    fclose(f);

    char* str = tmpnam(NULL);
    assert(strncmp("/tmp/file", str, 9) == 0);
  }

  FILE *n = fopen("/dev/null", "w");
  printf("5 bytes to dev/null: %d\n", fwrite(data, 1, 5, n));
  fclose(n);

  printf("ok.\n");

  return 0;
}
Exemple #30
0
static int gaa_internal_get_next_str(FILE *file, gaa_str_node *tmp_str, int argc)
{
    int pos_ini;
    int a;
    int i = 0, len = 0, newline = 0;

    if(argc == 1) {
        newline = 1;
        len = 2;
    }
    
    a = fgetc( file);
    if (a == EOF) return 0;

    while(a == ' ' || a == 9 || a == '\n')
    {
        if(a == '\n')
        {
            newline=1;
            len = 2;
        }
        a = fgetc( file);
        if (a == EOF) return 0;
    }

    pos_ini = ftell(file) - 1;

    while(a != ' ' && a != 9 && a != '\n')
    {

        len++;
        a = fgetc( file);
        if(a==EOF) return 0; //a = ' ';
    }

    len += 1;
    tmp_str->str = gaa_malloc((len) * sizeof(char));

    if(newline == 1)
    {
        tmp_str->str[0] = '-';
        tmp_str->str[1] = '-';
        i = 2;
    }
    else
    {
        i = 0;
    }

    fseek(file,pos_ini, SEEK_SET);
    do
    {
        a = fgetc( file);

        if (a == EOF) {
            i+=2;
            break;
        }
        tmp_str->str[i] = a;
        i++;
    }
    while(a != ' ' && a != 9 && a != '\n' && i < len);

    tmp_str->str[i - 1] = 0;

    fseek(file,- 1, SEEK_CUR);
/*    printf("%d\n", ftell(file)); */
    
    return -1;
}