unsigned char* FileSystem::LoadFileContents(std::string filename, bool path_is_absolute) {
	
	std::string filepath = filename;
	if (!path_is_absolute) {
		filepath = getFullFilePath(filename);
	}

	std::ifstream file;
	file.open(filepath, std::ios::in);
	unsigned long len = getFileLength(file);

	unsigned char* shaderSrc = (unsigned char*) new char[len+1];
	shaderSrc[len] = 0;  // len isn't always strlen cause some characters are stripped in ascii read...
	// it is important to 0-terminate the real length later, len is just max possible value...

	unsigned int i=0;
	while (file.good())
	{
		shaderSrc[i++] = file.get();       // get character from file
		if (i>len) i=len;				   // coding guidelines...
	}

	shaderSrc[i] = 0;  // 0 terminate it.
	file.close();

	return shaderSrc;
}
static uint8_t *
readFile(const char *path, const char *name, int32_t &length, char &type) {
    char filename[1024];
    FILE *file;
    uint8_t *data;
    UErrorCode errorCode;
    int32_t fileLength, typeEnum;

    makeFullFilename(path, name, filename, (int32_t)sizeof(filename));

    /* open the input file, get its length, allocate memory for it, read the file */
    file=fopen(filename, "rb");
    if(file==NULL) {
        fprintf(stderr, "icupkg: unable to open input file \"%s\"\n", filename);
        exit(U_FILE_ACCESS_ERROR);
    }

    /* get the file length */
    fileLength=getFileLength(file);
    if(ferror(file) || fileLength<=0) {
        fprintf(stderr, "icupkg: empty input file \"%s\"\n", filename);
        fclose(file);
        exit(U_FILE_ACCESS_ERROR);
    }

    /* allocate the buffer, pad to multiple of 16 */
    length=(fileLength+0xf)&~0xf;
    data=(uint8_t *)malloc(length);
    if(data==NULL) {
        fclose(file);
        exit(U_MEMORY_ALLOCATION_ERROR);
    }

    /* read the file */
    if(fileLength!=(int32_t)fread(data, 1, fileLength, file)) {
        fprintf(stderr, "icupkg: error reading \"%s\"\n", filename);
        fclose(file);
        free(data);
        exit(U_FILE_ACCESS_ERROR);
    }

    /* pad the file to a multiple of 16 using the usual padding byte */
    if(fileLength<length) {
        memset(data+fileLength, 0xaa, length-fileLength);
    }

    fclose(file);

    // minimum check for ICU-format data
    errorCode=U_ZERO_ERROR;
    typeEnum=getTypeEnumForInputData(data, length, &errorCode);
    if(typeEnum<0 || U_FAILURE(errorCode)) {
        fprintf(stderr, "icupkg: not an ICU data file: \"%s\"\n", filename);
        free(data);
        exit(U_INVALID_FORMAT_ERROR);
    }
    type=makeTypeLetter(typeEnum);

    return data;
}
int loadshader(char* filename, GLchar** ShaderSource)
{
    unsigned long len;
    std::ifstream file;
    file.open(filename, std::ios::in); // opens as ASCII!
    if(!file) return -1;
    
    len = getFileLength(file);
    
    if (len==0) return -2;   // Error: Empty File 
    
    *ShaderSource = (char*) new char[len+1];
    if (*ShaderSource == 0) return -3;   // can't reserve memory
    
    // len isn't always strlen cause some characters are stripped in ascii read...
    // it is important to 0-terminate the real length later, len is just max possible value... 
    *ShaderSource[len] = 0; 
    
    unsigned int i=0;
    while (file.good())
    {
        *ShaderSource[i] = file.get();       // get character from file.
        if (!file.eof())
            i++;
    }
    
    *ShaderSource[i] = 0;  // 0-terminate it at the correct position
    
    file.close();
    
    return 0; // No Error
}
Exemple #4
0
int loadShader(const char* filename, char** shaderSource, unsigned long len)
{
	std::ifstream f;

	f.open(filename, std::ios::in);
	if (!f) return -1;

	len = getFileLength(f);
	if (len == 0) return -2;

	*shaderSource = new char[len + 1];
	if (*shaderSource == 0) return -3;

	*shaderSource[len] = 0;

	unsigned int i = 0;
	while (f.good())
	{
		*shaderSource[i] = f.get();
		if (!f.eof())
			++i;
	}
	*shaderSource[i] = 0;

	f.close();

	return 1;
}
Exemple #5
0
int loadShader(char* filename, GLchar** ShaderSource, int * len) {
    ifstream file;
    printf("Shader file: %s\n", filename);
    file.clear();
    file.open(filename, ios::binary);
    if(!file)
        return -1;

    (*len) = getFileLength(file);

    if((*len)==0)
        return -2;

    if(((*ShaderSource) = new char[(*len)+1]) == 0)
        return -3;
    (*ShaderSource)[(*len)] = 0;

    unsigned int i=0;
    while(file.good()) {
        (*ShaderSource)[i] = file.get();
        if(!file.eof())
            i++;
    }
    (*ShaderSource)[i] = 0;

    file.close();
    return 0;
}
Exemple #6
0
	int Shader::loadShaderSource(const char* fileName, GLchar** shaderSource, unsigned long& len)
	{
		std::ifstream file;
		file.open(fileName, std::ios::in);
		if (!file)return -1;

		(len) = getFileLength(file);

		if (len == 0) return -2;

		*shaderSource = new char[len + 1];
		if (*shaderSource == 0) return -3;

		(*shaderSource)[len] = 0;

		unsigned i = 0;
		while (file.good())
		{
			(*shaderSource)[i] = file.get();       // get character from file.
			if (!file.eof())
				i++;
		}

		(*shaderSource)[i] = 0;//line terminator

		file.close();

		return 0;
	}
Exemple #7
0
void Server::waitForClient()
{

    printf("Waiting for client.\n");

	serialReceive(msgBuffer); // Recieve filename from client.

    FILE* stream;

    if(stream = fopen(msgBuffer, "r"))      // If opening a file with the name recieved is succesfull continue
    {
        long lengthOfFile = getFileLength(stream);      // Get file length of opened file in bytes.

        printf("User requested: %s with a size of %ld bytes\n", msgBuffer, lengthOfFile); // Print out filename and lenght of file.

        sprintf(msgBuffer, "%ld", lengthOfFile); // Convert lenght of file to string.

		serialSend(msgBuffer, strlen(msgBuffer)+1); // Send lenght of file


        sendFile(stream, lengthOfFile);     // Use function to send file, giving pointer and lenght of the file to send.

        fclose(stream);  // Close file.
    }
    else // If file couldnt be found, print out message and send to client 0 filelenght (its not found).
    {
        printf("Client tried to get: %s\n", msgBuffer);
        serialSend("0", 2);
    }

    printf("Client connection closed\n");
}
Exemple #8
0
int glsl_shader_load(int id, string fname)
{
  ifstream file;
  file.open(fname.c_str(), ios::in); // opens as ASCII
  if (!file.is_open()) return 1; // Error: File could not be oppenned

  unsigned long len = getFileLength(file);
  if (len == 0) return 2;   // Error: Empty File 
  
  GLchar* ShaderSource;
  ShaderSource = (GLchar*) new char[len+1];

  ShaderSource[len] = 0;

  unsigned int i=0;
  while (file.good())
  {
    ShaderSource[i] = file.get();       // get character from file.
    if (!file.eof())
    i++;
  }
    
  ShaderSource[i] = 0;  // 0-terminate it at the correct position

  glShaderSource(shaders[id]->shader, 1, (const GLchar**)&ShaderSource, NULL);

  file.close();
  return 3; // No Error
}
void FileIO::fileConstructor()
{
   lineCounter = 0;
   dataCounter = 0;
   isOpen = true;
   getFileLength();
}
Exemple #10
0
unsigned char *_XResourcePack::getFileData(const char *filename)
{
	if(filename == NULL) return NULL;
	int lengthTemp = getFileLength(filename);
	if(lengthTemp <= 0) return NULL;
	unsigned char *p = NULL;
	if((p = createArrayMem<unsigned char>(lengthTemp + 1)) == NULL) return NULL;
	_XResourcePack::GetInstance().unpackResource(filename,p);
	*(p + lengthTemp) = '\0';
	return p;
}
Exemple #11
0
// -Server functions
void Server::waitForClient()
{
    // Set to wait for '1' client
    listen(socketListener, 1);

    // Wait and connect
    printf("Waiting for client.\n");
    currentConnection = accept(socketListener, (sockaddr *)&clientInfo, (socklen_t*)&socketSize);

    // Do stuff
    // -Test
    printf("Someone connected from: %s\n", inet_ntoa(clientInfo.sin_addr)); // Someone connected
    //send(currentConnection, "Hello", 5, 0);

    // Receive file request
    recv(currentConnection, msgBuffer, BUFFERSIZE, 0); // Note: Assume is null terminated


    // Open and send file
    FILE* stream;

    if(stream = fopen(msgBuffer, "r"))
    {
        // Send info to client about file found and its size and ask if want it
        long lengthOfFile = getFileLength(stream);

        printf("User requested: %s with a size of %ld bytes\n", msgBuffer, lengthOfFile);

        // -Sending file size
        sprintf(msgBuffer, "%ld", lengthOfFile);
        send(currentConnection, msgBuffer, strlen(msgBuffer)+1, 0); // + 1 since want null terminator

        // -Get response
        recv(currentConnection, msgBuffer, BUFFERSIZE, 0); // Note: Assume is null terminated

        if(!strcmp(msgBuffer, "Ok")) // Returns '0' if equal
        {
            sendFile(stream, currentConnection, lengthOfFile);
        }

        // Cleaning
        fclose(stream);
    }
    else
    {
        // Can here send msg to client about file not found
        printf("Client tried to get: %s\n", msgBuffer);
        send(currentConnection, "0", 2, 0); // 2 in size since null terminated
    }

    // Close
    close(currentConnection);
    printf("Client connection closed\n");
}
/*
** This function loads the message data into an allocated buffer.
** It also sets the first characters to indicate the size of the message data.
*/
char *loadMessageData(char *filePath, int *messageSize, int numSizeDigits, int bytesPerSect)
{
	FILE *fp;
	int fileLength;
	char *ret;
	char temp[20];

	/* Attempt to open the message data file. */
	fp = fopen(filePath, "rb");
	if (fp == NULL)
	{
		/* Bail out since the file did not open. */
		return(NULL);
	}

	/* Get the file size. */
	fileLength = getFileLength(fp);

	/* Buffer will be an even multiple of sector size. */
	int bytesToAllocate = fileLength + numSizeDigits;
	int sectorsToAllocate = bytesToAllocate / bytesPerSect;
	if (bytesToAllocate % bytesPerSect != 0) sectorsToAllocate++;
	bytesToAllocate = sectorsToAllocate * bytesPerSect;

	/* Attempt to allocate the message data buffer.
	We need to also allocate additional space for the message size. */
	ret = (char *)calloc(bytesToAllocate, sizeof(char));
	if (ret == NULL)
	{
		/* Buffer did not allocate so we close
		the file and return NULL. */
		fclose(fp);
		return(NULL);
	}

	/* Read the message data into the buffer. We skip the first
	several bytes of the return buffer where the size data
	will reside. */
	fread(&ret[numSizeDigits], sizeof(char), fileLength, fp);
	fclose(fp);

	/* Here we paste the size (with length of 5, and zero padded) into
	the first part of the message. The size becomes part of the message. */
	sprintf(temp, formats[numSizeDigits], fileLength);
	strncpy(ret, temp, numSizeDigits);

	/* Set the messageSize variable to indicate the full buffer size. */
	*messageSize = fileLength + numSizeDigits;

	/* Return the message buffer. */
	return(ret);
}
Exemple #13
0
void initEditor(FILE *fp, const char *filename) {
    getFileLength(fp, &_len);

    _fp = fp;
    _filename = filename;

    _pos = malloc(sizeof(struct Position));
    _pos->row = 0;
    _pos->col = 0;

    _fileBuffer = malloc(sizeof(char) * _len);
    getContent(_fp, _fileBuffer, _len);
}
int ShaderManager::loadFile(int type, const char *filename, char** source, int *len)
{
	std::ifstream file;
	//char* source;
	//unsigned len;
	file.open(filename, std::ios::in); // opens as ASCII!
	if(!file)
	{
		std::cout << "Shader of type " << type << " could not be opened: " << filename << std::endl;
		return -1;
	}

	*len = getFileLength(file);

	if (*len == 0)
	{
		// Error: Empty File 
		std::cout << "Shader of type " << type << " is empty: " << filename << std::endl;
		return -2;
	}

	(*source) = new char[*len+1];
	if ((*source) == 0)
	{
		std::cout << "New failed." << std::endl;
		return -3;   // can't reserve memory
	}

	// len isn't always strlen cause some characters are stripped in ascii read...
	// it is important to 0-terminate the real length later, len is just max possible value... 
	(*source)[*len] = 0; 

	unsigned int i=0;
	while (file.good())
	{
		(*source)[i] = file.get();       // get character from file.
		if (!file.eof())
			i++;
	}

	(*source)[i] = 0;  // 0-terminate it at the correct position

	file.close();

	std::cout << "Shader of type " << type << " opened and read successfully: " << filename << std::endl;

	//std::pair<char*, unsigned long> ShaderAttributes(*source, *len);
	//Shaders[type][filename] = ShaderAttributes;
	return 0; // No Error
}
Exemple #15
0
int loadProgram(FILE *file, char program[])
{
    int c;

    if (file) 
    {
        fread(program, sizeof(char), getFileLength(file), file);
        return 0;
    }
    else
    {
        return -1;
    }
}
Exemple #16
0
/*
 * Opens the config file and reads it out
 */
void parseFile(const char *fileName,
               struct system *System,
               struct tip *Tip,
               struct space *Space,
               struct graphene *Graphene,
               struct substrate *Substrate)
{
	FILE *fp;
	char *buffer;
	size_t fileLength = 0;

	fp = fopen(fileName, "r");

	if (fileName == NULL)
	{
		fprintf(stderr, "Error: No config file specified! \n");
		exit(EXIT_FAILURE);
	}
	else if (fp == NULL)
	{
		perror(fileName);
		exit(EXIT_FAILURE);
	}
	else
	{
		fileLength = getFileLength(fp);

		if(fileLength < MAXSIZE_FILE)
		{
			buffer = (char *) calloc(fileLength, sizeof(char));
			assert(buffer != NULL);
			fread(buffer, fileLength, (size_t) 1, fp);
			fclose(fp);
			getObjects(buffer, System, Tip, Space, Graphene, Substrate);
			free(buffer);
		}
		else
		{
			fprintf(stderr, "Error: File is too big! \n");
			exit(EXIT_FAILURE);
		}
	}
}
Exemple #17
0
void FileFrame::LoadChunk(std::string& filename )
{
    //open file, seek to end to find file length
    FILE* loader = fopen(filename.c_str(), "rb");
    
    int filesize = getFileLength(filename);
	if( filesize == -1 )	
	{
		printf("Nonexistent file.\n");
		return;
	}

    int chunkSize = 0;
    if(filesize < c_MaxChunkSize)
        chunkSize  = filesize; 
    else
        chunkSize  = c_MaxChunkSize;

    m_TotalChunks = (filesize/chunkSize) + (filesize%chunkSize == 0 ? 0 : 1);

    int packetSize = 0;
    if (chunkSize < c_MaxPacketSize)
        packetSize = chunkSize;
    else
        packetSize = c_MaxPacketSize;
        
    m_Chunk.m_TotalPackets = chunkSize/packetSize + (chunkSize % packetSize == 0 ? 0 : 1);


    fseek(loader, m_CurrentChunk*chunkSize, SEEK_SET);
   
    char* readBuf = new char[chunkSize];
    int bytes_read = fread((void*)readBuf, sizeof(char), chunkSize, loader);

    m_Chunk.m_Array.clear();
    for(int i = 0; i < bytes_read; ++i )
    {
        m_Chunk.m_Array.push_back(readBuf[i]); 
    }
    fclose(loader);
    ++m_CurrentChunk;
	this->m_Chunk.m_CurrentPacket = -1;
}
Exemple #18
0
int Shader::Load(char* filename)
{
    m_filename = std::string(filename);
    
    std::cout << "in load";
    
    std::ifstream file;
    std::cout << filename;
	file.open(filename, std::ios::in);
    if (!file)
    {
        char err[512];
        sprintf(err, "Failed to load shader: %s", filename);
        return -1;
    }
    
    unsigned long len = getFileLength(file);
    
    if (len == 0) return -2;
    
    m_source = (char *)malloc(len + 1);
    
    std::cout << " after malloc";
    
    m_source[len] = 0;  // len isn't always strlen because some characters are stripped in ASCII read
    // it is important to null-terminate the real length later; len is just max possible value
    unsigned int i=0;
    while (file.good())
    {
        m_source[i] = file.get();
        if (!file.eof())
            i++;
    }
    
    m_source[i] = 0;
    std::cout << "m_source: ";
    std::cout << m_source[1];
    
    file.close();
    
    return 0;
}
Exemple #19
0
int UnZip::getTotalFilesSize()
{
	int totallen = 0;
	for(int i = 0;i < itemNum;i++)
	{
		int len = getFileLength(i);
		if(len >= 0)
		{
			totallen += len;
		}
		else
		{
			unpackSize = -1;
			break;
		}
	}
	unpackSize = totallen;

	return unpackSize;
}
const char* readFile(const char* filename)
{
    std::ifstream file;
    file.open(filename, std::ios::in);

    if (!file)
    {
        return NULL;
    }

    // get length of file
    unsigned long length = getFileLength(file);
    char* buffer = new char[length + 1];

    if (buffer == NULL)
    {
        return NULL;
    }

    buffer[length] = '\0';

    // fill buffer
    unsigned int i = 0;

    while (file.good())
    {
        buffer[i] = file.get();

        if (!file.eof())
        {
            i++;
        }
    }

    buffer[i] = '\0';
    file.close();
    return buffer;
}
		char * CShader::loadShader(const char * filename)
		{
			char * shaderSrc = NULL;
			ifstream file;
			file.open(filename,ios::in); //opens as ascii
			if(!file)
			{
				std::cout<<"File "<<filename<<" could not be opened"<<std::endl;
				return NULL;
			}
			unsigned long length = 0;
			length  = getFileLength(file);
			if(length == 0) //error: empty file
			{
				std::cout<<"File "<<filename<<" is empty"<<std::endl;
				return NULL;
			}
				
			shaderSrc = (char *) new char[length+1];
			if(shaderSrc == 0)
				return NULL;
			shaderSrc[length] = 0;
			 
			unsigned int i = 0;
			while(file.good())
			{
				shaderSrc[i] = file.get();
				if(!file.eof())
					i++;
			}

			shaderSrc[i] = 0; //zero/null terminator
			file.close();
			
			std::cout<<"Shader file:" << filename <<" loaded succesfully "<<std::endl;
			return shaderSrc;
		}
char* loadFile(const char *fileName)
{
    std::ifstream file;
    file.open(fileName, std::ios::in);
    if (!file) {
        std::cerr << "could not open file " << fileName << std::endl;
        GLchar *shaderSource = (GLchar*) new char[1];
        shaderSource[0]=0;
        return shaderSource;
    }

    unsigned long len = getFileLength(file);
    if (len == 0) {

        GLchar *shaderSource = (GLchar*) new char[1];
        shaderSource[0]=0;
        return shaderSource;

    }

    GLchar *shaderSource = (GLchar*) new char[len+1];

    // len isn't always strlen cause some characters are stripped in ascii read...
    // it is important to 0-terminate the real length later, len is just max possible value...
    shaderSource[len] = 0;
    unsigned int i = 0;
    while (file.good()) {
        // get character from file.
        shaderSource[i] = file.get();
        if (!file.eof()) i++;
    }

    shaderSource[i] = 0;  // 0 terminate it.
    file.close();
    return shaderSource;
}
Exemple #23
0
int main(int argc, char *argv[])
{
   char hostname[100];
   char buf[BUFSIZE];
   char query[BUFSIZE];
   char msg_id;
   //char msg[MSG_SIZE];
   std::string msg = "";
   std::string extractedMsg = "";
   int sd;
   int port;
   int count, cur_count;
   int length;
   bool isDone = false;
   struct sockaddr_in pin;
   struct hostent *hp;

   /* check for command line arguments */
   if (argc != 3)
   {
      printf("Usage: client host port\n");
      exit(1);
   }

   /* get hostname and port from argv */
   strcpy(hostname, argv[1]);
   port = atoi(argv[2]);

   /* create anhi broke mine a bit
    Internet domain stream socket */
   if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
      perror("Error creating socket");
      exit(1);
   }

   /* lookup host machine information */
   if ((hp = gethostbyname(hostname)) == 0) {
      perror("Error on gethostbyname call");
      exit(1);
   }

   /* fill in the socket address structure with host information */
   memset(&pin, 0, sizeof(pin));
   pin.sin_family = AF_INET;
   pin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
   pin.sin_port = htons(port); /* convert to network byte order */


   printf("Connecting to %s:%d\n\n", hostname, port);

   /* connect to port on host */
   if (connect(sd,(struct sockaddr *)  &pin, sizeof(pin)) == -1) {
      perror("Error on connect call");
      exit(1);
   }
   /* ask user for a selection */
   printf("Input your selection using one letter in {L,R,P,D,T,Q}.\n");
   printf("L: Turn Rover Left 90 degrees.\n");
   printf("R: Turn Rover Right 90 degrees.\n");
   printf("P: Take a Picture of the martian ASCII landscape.\n");
   printf("D: Return the direction the rover is facing.\n");
   printf("T: Return the air temperature at the rover's location.\n");
   printf("Q: Quit.\n");

   while(!isDone)
   {
		msg = "";
		extractedMsg = "";
	   gets(query);
	   if(query[0] == 'Q' || query[0] == 'q') {
	      isDone = true;
	   }
	   
	   /* send the query to the server */
	   if ( (count = write(sd, query, strlen(query)+1)) == -1) {
	      perror("Error on write call");
	      exit(1);
	   }
	   printf("Client sent %d bytes\n", count);
	   
		/* wait for a message to come back from the server */
		if ( (count = read(sd, buf, BUFSIZE)) == -1) {
			perror("Error on read call");
			exit(1);
		}
		printf("Client read %d bytes\n", count);

		length = getFileLength(buf);
		//printf("Length %d.\n", length);
		//printf("buf is: %s\n", buf);
		msg = extractMsg(buf);
		//printf("Msg is: %s\n", msg.c_str());
		cur_count = count;
		msg_id = buf[0];
		while (cur_count < length)
		{
			if ( (count = read(sd, buf, BUFSIZE)) == -1) {
				perror("Error on read call");
				exit(1);
			}
			printf("Client read %d bytes\n", count);
			if (cur_count < (length -1))
			{
			 	std::string buffer(buf);
				std::string buffer2 = buffer.substr(0, (std::string::npos - 1));
				memcpy(buf,buffer2.c_str(),buffer2.size());
			}
			msg += buf;
	                //printf("buf is: %s\n", buf);
			//printf("Msg is: %s\n", msg.c_str());
			cur_count += count;
		}
		if (msg_id == 'P' || msg_id == 'p')
		{
			std::ofstream output("MARS_ROVER_IMAGE.jpg", std::fstream::binary);
			output.write(msg.c_str(), length);
			output.close();
			printf("Client read image to MARS_ROVER_IMAGE.jpg in the current directory.\n");
		}
		else
		{
			printf("\n\n%s\n\n", msg.c_str());
		}
   }

   /* close the socket */
   close(sd);
   exit(0);
}
Exemple #24
0
bool UpdateManager::downloadFile(int index)
{
	

	this->downloadIndex=index;
	VersionInfo vi=downloadInfo[index];
	string filename=vi.getFullpath();//getFileFullName(vi.getPath());
	createDirForFile(filename);
	long sourcesLength=vi.getFileLength();
	int fileLength=getFileLength(filename);
	if(sourcesLength==fileLength)
		return true;
	CCLog("downloadFile name is %s,path is %s",vi.getName(),vi.getPath());
	CCLog("filename is %s",filename.c_str());
	
	FILE* f;
	if(fileLength&&getFileExtention(filename)==string("apk"))
	{
		f=fopen(filename.c_str(),"ab+");
		
	}
	else
	{
		f=fopen(filename.c_str(),"wb");
	}
	if(!f)
	{
		MessageInfo *networkerror=new MessageInfo();
		networkerror->obj=this->protocol;
		networkerror->what=MessageInfo::CREATE_FILE_FAILED;
		this->helper->sendMessage(networkerror);
		CCLog("file pointer create failed");
		return false;
	}
	CURLcode res;
	curl_easy_setopt(curl, CURLOPT_URL,vi.getPath());
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeFile);
	//curl_easy_setopt(curl,CURLOPT_RESUME_FROM_LARGE,fileLength?fileLength:0);
	if(getFileExtention(filename)==string("apk"))
	{
		char temp[64]={0};
		SPRINTF(temp,"%d-",fileLength);
		curl_easy_setopt(curl, CURLOPT_RANGE,temp);
	}
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, f);
	curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);
	curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, assetsManagerProgressFunc);
	curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, this);
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeOut);
	res = curl_easy_perform(curl);
	if (res != 0)
	{
		CCLog("error when download package");
		fclose(f);
		MessageInfo *networkerror=new MessageInfo();
		networkerror->obj=this->protocol;
		networkerror->what=MessageInfo::NET_WORK_ERROR;
		this->helper->sendMessage(networkerror);
		CCLog("downloadFile fialed network error");
		return false;
	}
	
	CCLog("succeed downloading file %s",filename.c_str());

	fclose(f);
	//发送消息,下载成功
	MessageInfo *msg=new MessageInfo();
	msg->what=MessageInfo::ONE_SUCCEED;
	msg->obj=this->protocol;
	msg->filename=string(vi.getName());
	msg->md5=vi.getMd5();
	msg->respath=vi.getRespath();
	helper->sendMessage(msg);
	
	return true;
}
Exemple #25
0
void* UpdateManager::downloadUncompressCopy(void* args)
{
	CCLog("---------------------->UpdateManager::downloadUncompressCopy");
	UpdateManager* mgr=(UpdateManager*)(args);
	//获取下载的路径
	for(unsigned int i=0;i<mgr->downloadInfo.size();++i)
	{
		string url=string(mgr->downloadInfo[i].getPath());
		if(mgr->getFileExtention(url)==string("apk"))
		{
			mgr->downloadInfo[i].setResPath(APKPATH);
			string respath=mgr->downloadInfo[i].getRespath();
			mgr->downloadInfo[i].setFullpath(resourcesPath+respath+"/jieji.apk");
		}
		else
		{
			mgr->downloadInfo[i].setResPath(getFileResName(url));
			string respath=mgr->downloadInfo[i].getRespath();
			mgr->downloadInfo[i].setFullpath(resourcesPath+respath);
		}
		
	}

	for(int i=0;i<(int)(mgr->downloadInfo.size());++i)
	{
		VersionInfo vi=mgr->downloadInfo[i];
		CCLog("name is %s,path is %s,respath is %s,fullpath is %s",vi.getName(),vi.getPath(),vi.getRespath().c_str(),vi.getFullpath().c_str());
	}


	mgr->curl = curl_easy_init();
	//开始获取下载的大小
	   
	MessageInfo * startGetMessage=new MessageInfo();
	startGetMessage->what=MessageInfo::START_GETMESSAGE;
	startGetMessage->obj=mgr->protocol;
	mgr->helper->sendMessage(startGetMessage);

	for(unsigned int i=0;i<mgr->downloadInfo.size();++i)
	{
		long remoteFileLength=getRemoteFileLength(mgr->downloadInfo[i].getPath(),mgr->curl);
		if(-1==remoteFileLength)
		{
			MessageInfo *networkerror=new MessageInfo();
			networkerror->obj=mgr->protocol;
			networkerror->what=MessageInfo::NET_WORK_ERROR;
			mgr->helper->sendMessage(networkerror);
			curl_easy_cleanup(mgr->curl);
			CCLog("------downloadUncompressCopy---get download message failed!");
			return NULL;
		}
		mgr->downloadInfo[i].setFileLength(remoteFileLength);
	}
	for(unsigned int i=0;i<mgr->downloadInfo.size();++i)
	{
		VersionInfo vi=mgr->downloadInfo[i];
		mgr->allToBeDownload+=vi.getFileLength();
	}
	curl_easy_cleanup(mgr->curl);
	
	MessageInfo* msg=new MessageInfo();
	msg->what=MessageInfo::STARTDOWNLOAD;
	msg->obj=mgr->protocol;
	mgr->helper->sendMessage(msg);

	
	mgr->curl = curl_easy_init();
	if (! mgr->curl)
	{
		CCLog("can not init curl");
		return NULL;
	}
	for(unsigned int i=0;i<mgr->downloadInfo.size();++i)
	{
		bool state=mgr->downloadFile(i);
		if(!state)
		{
			curl_easy_cleanup(mgr->curl);
				CCLog("------downloadUncompressCopy---download file failed!");
			return NULL;
		}
		
	}
	curl_easy_cleanup(mgr->curl);


	MessageInfo *msgdownloadsucceed=new MessageInfo();
	msgdownloadsucceed->what=MessageInfo::DOWNLOAD_SUCCEED;
	msgdownloadsucceed->obj=mgr->protocol;
	mgr->helper->sendMessage(msgdownloadsucceed);
	/*
	for(unsigned int i=0;i<mgr->downloadInfo.size();++i)
	{
		bool re=mgr->uncompressFile(i);
		if(!re)
		{
			MessageInfo *compress=new MessageInfo();
			compress->what=MessageInfo::UNCOMPRESS_FAILED;
			compress->obj=mgr->protocol;
			mgr->helper->sendMessage(compress);

			CCLog("------------>uncompressed file failed");
			return NULL;
		}
	}*/

	MessageInfo * uncompresssucceed=new MessageInfo();
	uncompresssucceed->obj=mgr->protocol;
	uncompresssucceed->what=MessageInfo::UNCOMPRESS_SUCCEED;
	mgr->helper->sendMessage(uncompresssucceed);


	////////开始复制文件了
	string sopath=resourcesPath+"/"+DOWNSOPATH;
	CCLog("--------->so de path is %s",sopath.c_str());
	FILE *fso=fopen(sopath.c_str(),"rb");
	

	string usepath=USESOPATH;
	bool createfolder=createDirectory(usepath.c_str());
	string sotouse(USESOPATH);
	sotouse=sotouse+"/libgame.so";
	CCLog("write path is %s",sotouse.c_str());


	FILE *writeso=fopen(sotouse.c_str(),"wb");
	if(fso&&writeso)
	{
		int len=getFileLength(sopath);
		int times=len/(8192);
		int last=len%(8192);
		char buffer[8192]={0};
		for(int i=0;i<times;i++)
		{
			fread(buffer,1,8192,fso);
			fwrite(buffer,1,8192,writeso);
		}
		fread(buffer,1,last,fso);
		fwrite(buffer,1,last,writeso);
		fclose(writeso);
		fclose(fso);
		mgr->haveSo=true;
		CCLog("-----------------copy succeed ");
	}
	else
	{
		CCLog("not have the file");
	}

	/***********************************************************/
	//删除文件吧1.下载的temp文件的zip文件,2..so文件
	MessageInfo *deleteSomething=new MessageInfo();
	deleteSomething->what=MessageInfo::DELETE_SOMETHING;
	deleteSomething->arg1=mgr->haveSo;
	mgr->helper->sendMessage(deleteSomething);






	MessageInfo* allsucceed=new MessageInfo();
	allsucceed->what=MessageInfo::ALL_SUCCEED;
	allsucceed->obj=mgr->protocol;
	allsucceed->arg1=mgr->haveApk;
	allsucceed->arg2=mgr->haveSo;
	mgr->helper->sendMessage(allsucceed);
	



	return NULL;
}
/*******************************************************************************
**
** Function         StartPatchDownload
**
** Description      Reads configuration settings, and begins the download
**                  process if patch files are configured.
**
** Returns:         None
**
*******************************************************************************/
static void StartPatchDownload(UINT32 chipid)
{
    ALOGD ("%s: chipid=%lx",__FUNCTION__, chipid);

    char chipID[30];
    sprintf(chipID, "%lx", chipid);
    ALOGD ("%s: chidId=%s", __FUNCTION__, chipID);

    readOptionalConfig(chipID);     // Read optional chip specific settings
    readOptionalConfig("fime");     // Read optional FIME specific settings
    getNfaValues(chipid);                 // Get NFA configuration values into variables

    findPatchramFile(FW_PATCH, sPatchFn, sizeof(sPatchFn));
    findPatchramFile(FW_PRE_PATCH, sPrePatchFn, sizeof(sPatchFn));

    {
        FILE *fd;
        /* If an I2C fix patch file was specified, then tell the stack about it */
        if (sPrePatchFn[0] != '\0')
        {
            if ((fd = fopen(sPrePatchFn, "rb")) != NULL)
            {
                UINT32 lenPrmBuffer = getFileLength(fd);

                if ((sI2cFixPrmBuf = malloc(lenPrmBuffer)) != NULL)
                {
                    size_t actualLen = fread(sI2cFixPrmBuf, 1, lenPrmBuffer, fd);
                    if (actualLen == lenPrmBuffer)
                    {
                        ALOGD("%s Setting I2C fix to %s (size: %lu)", __FUNCTION__, sPrePatchFn, lenPrmBuffer);
                        HAL_NfcPrmSetI2cPatch((UINT8*)sI2cFixPrmBuf, (UINT16)lenPrmBuffer, 0);
                    }
                    else
                        ALOGE("%s fail reading i2c fix; actual len=%u; expected len=%lu", __FUNCTION__, actualLen, lenPrmBuffer);
                }
                else
                {
                    ALOGE("%s Unable to get buffer to i2c fix (%lu bytes)", __FUNCTION__, lenPrmBuffer);
                }

                fclose(fd);
            }
            else
            {
                ALOGE("%s Unable to open i2c fix patchfile %s", __FUNCTION__, sPrePatchFn);
            }
        }
    }

    {
        FILE *fd;

        /* If a patch file was specified, then download it now */
        if (sPatchFn[0] != '\0')
        {
            UINT32 bDownloadStarted = false;

            /* open patchfile, read it into a buffer */
            if ((fd = fopen(sPatchFn, "rb")) != NULL)
            {
                UINT32 lenPrmBuffer = getFileLength(fd);
                ALOGD("%s Downloading patchfile %s (size: %lu) format=%u", __FUNCTION__, sPatchFn, lenPrmBuffer, NFC_HAL_PRM_FORMAT_NCD);
                if ((sPrmBuf = malloc(lenPrmBuffer)) != NULL)
                {
                    size_t actualLen = fread(sPrmBuf, 1, lenPrmBuffer, fd);
                    if (actualLen == lenPrmBuffer)
                    {
                        if (!SpdHelper::isPatchBad((UINT8*)sPrmBuf, lenPrmBuffer))
                        {
                            /* Download patch using static memeory mode */
                            HAL_NfcPrmDownloadStart(NFC_HAL_PRM_FORMAT_NCD, 0, (UINT8*)sPrmBuf, lenPrmBuffer, 0, prmCallback);
                            bDownloadStarted = true;
                        }
                    }
                    else
                        ALOGE("%s fail reading patchram", __FUNCTION__);
                }
                else
                    ALOGE("%s Unable to buffer to hold patchram (%lu bytes)", __FUNCTION__, lenPrmBuffer);

                fclose(fd);
            }
            else
                ALOGE("%s Unable to open patchfile %s", __FUNCTION__, sPatchFn);

            /* If the download never got started */
            if (!bDownloadStarted)
            {
                /* If debug mode, fail in an obvious way, otherwise try to start stack */
                postDownloadPatchram(SpdHelper::isSpdDebug() ? HAL_NFC_STATUS_FAILED :
                        HAL_NFC_STATUS_OK);
            }
        }
        else
        {
            ALOGE("%s: No patchfile specified or disabled. Proceeding to post-download procedure...", __FUNCTION__);
            postDownloadPatchram(HAL_NFC_STATUS_OK);
        }
    }

    ALOGD ("%s: exit", __FUNCTION__);
}
Exemple #27
0
///Reads a chunk of the file into a buffer.
bool XTail::readChunk(__int64  start, __int64  end, LPWSTR out, int maxSize)
{
	bool val = true;

	swprintf_s(tbuffer, L"in readChunk Start: %I64i, End: %I64i, Max: %i\n", start, end, maxSize);
	logger->debug(tbuffer);

	getFileLength(filename);
	swprintf_s(tbuffer, L"File(%s) Length is: %I64i\n", filename, len);
	logger->debug(tbuffer);

	if (len < 1L)
	{
		MessageBoxW(NULL, L"Can not read file, no length.", L"IO Error", MB_OK);
		return false;
	}

	logger->debug("Opening file....\n");
	wifstream file;
	file.open(filename, ios::in | ios::binary);
	//FILE *file;
	//if (_wfopen_s(&file, filename, L"rb") != 0)
	if (file.bad() || file.fail())
	{
		swprintf_s(tbuffer, L"Can not open file(%s)", filename);
		MessageBoxW(NULL, tbuffer, L"IO Error", MB_OK);
		val = false;
		goto exit;
	}

	logger->debug("Seeking to beginning....\n");
	//_fseeki64(file, 0, SEEK_SET);
	file.seekg(0, ios::beg);

	//Ensure we can't read past the EOF
	swprintf_s(tbuffer, L"B4 BeginStream: %I64i, EndStream: %I64i, Start: %I64i, End: %I64i\n", 0, len, start, end);
	logger->debug(tbuffer);

	start += 0;
	end += 0;

	if (end > len) 
	{
		logger->debug("End > endStream, adjusting..\n");
		end = len;
	}

	if (start > len)
	{
		logger->debug("Start > endStream, adjusting..\n");
		start = end;
	}
	

	if (end - start > maxSize)
	{
		logger->debug("end - start > maxSize, adjusting..\n");
		end = start + maxSize;
	}

	swprintf_s(tbuffer, L"AFT BeginStream: %I64i, EndStream: %I64i, Start: %I64i, End: %I64i\n", 0, len, start, end);
	logger->debug(tbuffer);

	file.seekg(start);
	file.read(out, end-start);
	//if (_fseeki64(file, start, SEEK_SET) != 0)
	if (file.bad() || file.fail())
	{
		MessageBoxW(NULL, L"Read file failed.", L"IO Error", MB_OK);
		val = false;
		goto exit;
	}

	/**
	//if (fread_s(out, (int)(end-start), sizeof(wchar_t), (int)(end-start), file) != 0)
	{
		MessageBoxW(NULL, L"Read file failed. REAL READ", L"IO Error", MB_OK);
		val = false;
		goto exit;
	}
	*/


	out[(end-start)] = L'\0';



exit:
	if (file.is_open())
		file.close();
	//if (file)
//		fclose(file);

	return val;
}
Exemple #28
0
/**
 *  lädt eine BBM-File in ein ArchivInfo.
 *
 *  @param[in]  file    Dateiname der BBM-File
 *  @param[out] items   ArchivInfo-Struktur, welche gefüllt wird
 *
 *  @return Null bei Erfolg, ein Wert ungleich Null bei Fehler
 *
 *  @author FloSoft
 *  @author OLiver
 */
int libsiedler2::loader::LoadBBM(const std::string& file, ArchivInfo& items)
{
    char header[4], pbm[4];
    unsigned int chunk;
    unsigned int i = 0;

    if(file.empty())
        return 1;

    // Datei zum lesen öffnen
    boost::scoped_ptr<FILE> bbm(fopen(file.c_str(), "rb"));

    // hat das geklappt?
    if(!bbm)
        return 2;

    long size = getFileLength(bbm.get());

    // Header einlesen
    if(libendian::le_read_c(header, 4, bbm.get()) != 4)
        return 3;

    // ist es eine BBM-File? (Header "FORM")
    if(strncmp(header, "FORM", 4) != 0)
        return 4;

    // Länge einlesen
    unsigned length;
    if(libendian::le_read_ui(&length, bbm.get()) != 0)
        return 5;

    // Typ einlesen
    if(libendian::le_read_c(pbm, 4, bbm.get()) != 4)
        return 6;

    // ist es eine BBM-File? (Typ "PBM ")
    if(strncmp(pbm, "PBM ", 4) != 0)
        return 7;

    // Chunks einlesen
    while(!feof(bbm.get()) && ftell(bbm.get()) < size)
    {
        // Chunk-Typ einlesen
        if(libendian::be_read_ui(&chunk, bbm.get()) != 0)
            return 8;

        switch(chunk)
        {
            case 0x434D4150: // "CMAP"
            {
                // Länge einlesen
                if(libendian::be_read_ui(&length, bbm.get()) != 0)
                    return 9;

                // Bei ungerader Zahl aufrunden
                if(length & 1)
                    ++length;

                // Ist Länge wirklich so groß wie Farbtabelle?
                if(length != 256 * 3)
                    return 10;

                // Daten von Item auswerten
                ArchivItem_Palette* palette = (ArchivItem_Palette*)getAllocator().create(BOBTYPE_PALETTE);
                items.push(palette);

                size_t namePos = file.find_last_of('/');
                if(namePos != std::string::npos)
                {
                    std::stringstream rName;
                    rName << file.substr(namePos+1) << "(" << i << ")";
                    palette->setName(rName.str());
                }

                // Farbpalette lesen
                Color colors[256];
                if(libendian::le_read_uc(&colors[0].r, sizeof(colors), bbm.get()) != sizeof(colors))
                    return 10;

                // Farbpalette zuweisen
                for(unsigned int k = 0; k < 256; ++k)
                    palette->set(k, colors[k]);

                ++i;
            } break;
            default:
            {
                // Länge einlesen
                if(libendian::be_read_ui(&length, bbm.get()) != 0)
                    return 12;

                // Bei ungerader Zahl aufrunden
                if(length & 1)
                    ++length;

                if(length > 0)
                {
                    boost::scoped_array<unsigned char> buffer(new unsigned char[length]);

                    // überspringen
                    if(libendian::le_read_uc(buffer.get(), length, bbm.get()) != (int)length)
                        return 13;
                }
            } break;
        }
    }

    if(items.size() == 0)
        return 14;

    // alles ok
    return 0;
}
Exemple #29
0
/*-------------------- readFile --------------------*/
File_t
readFile 
(
    ParameterSpecification_t    fileSpecifier, /* in */
    const char                * filename       /* in */
)
{
    File_t                      returnValue;
    FILE                      * filePointer;
    long                        fileLength;

    if( FileOpened == openFileForReading( filename, &filePointer ) )
    {
        if( Success == getFileLength( filePointer, &fileLength ) )
        {
            void              * ptr;

            /*
             * Allocate one byte more if a newline must be added
             */
            if( Success == allocateBuffer( fileLength + 1 , &ptr ) )
            {
                char          * buffer = ( char * )ptr;

                if( Success == readFileToBuffer( filePointer, fileLength, &buffer ) )
                {

                    if ( FALSE == queryParameter( IgnoreEOF ) )
                    {
                        char  * eof = (buffer + fileLength - 1);

                        if ( *eof != '\n' )
                        {
                            *( eof + 1 ) = '\n';
                            fileLength++;
                        }
                    }

                    addToWatchdog( fileLength );
                    associateBuffer( fileSpecifier, fileLength, &buffer );
                    returnValue = FileOperationsSuccessful;
                }
                else
                {
                    freeBuffer( &buffer );
                    returnValue = FileOperationsFailed;
                }
            }
            else
            {
                returnValue = FileOperationsFailed;
            }
        }
        else
        {
            returnValue = FileOperationsFailed;
        }
        closeFile( filePointer );
    }
    else
    {
        returnValue = FileOperationsFailed;
    }

    return( returnValue );
}
Exemple #30
0
int writeDataToImage(IplImage *img, PixelMap *pixelmap, FILE *file, ConfigInfo config, unsigned int useable_pixels)
{

	CvScalar pixel;
	int index, number;
	int i,j, written_bytes=0;
	int message_length;
	unsigned int img_capacity;
	char byte;

	int img_channels = 0;

	if(img->nChannels == 1)
	{
		img_channels = 1;
	}
	if(img->nChannels >= 3){
		img_channels = 3;
	}

	img_capacity = (unsigned int)( ((useable_pixels * img_channels) - MESSAGE_LENGTH_BITS) / BYTE );

	message_length = getFileLength(file);

	if(img_capacity < message_length)
	{
		printf("Image capacity is only: %u Byte -> message size is: %d\n", img_capacity, message_length);
		return 0;
	}

	printf("Image capacity is: %u Byte\n", img_capacity);
	printf("Message size is: %d Byte\n", message_length);


	DEBUG( ("writing message length bits to image\n") );

	for(i=MESSAGE_LENGTH_BITS-1; i>=0; )
	{

		//get next free pixel
		do
		{
			number = getNextRandom();

			index = number % useable_pixels;
		}
		while( pixelmap[index].used == TRUE );

		//get values at this place
		pixel = cvGet2D(img, pixelmap[index].x_coord, pixelmap[index].y_coord);


		//if we have more than one channel
		for(j=0; j<img_channels; j++)
		{
			pixel.val[j] = LSB_BIT( (int)pixel.val[j],  ((message_length >> i) & 1) );

			DEBUG( ("%u", ((message_length >> i) & 1)) );

			i--;

			if(i < 0)
			{
				break;
			}
		}

		cvSet2D(img, pixelmap[index].x_coord, pixelmap[index].y_coord, pixel);

		pixelmap[index].used = TRUE;

	}
	DEBUG( ("\n") );

	getNextRandom();//fix -> asynchron


	/////////////////////////////////////////////////////////////////////////////
	DEBUG( ("writing bytes to image...") );

	j=3;

	while( (EOF != (byte = getByteFromFile(file))) && (written_bytes < img_capacity) && (written_bytes < message_length) )
	{

		for(i=BYTE-1; i>=0; )
		{
			if(j>=img_channels)
			{
				j=0;

				do
				{
					number = getNextRandom();

					index = number % useable_pixels;
				}
				while( pixelmap[index].used == TRUE );

				pixel = cvGet2D(img, pixelmap[index].x_coord, pixelmap[index].y_coord);
			}
			else
			{
				j++;
			}


			while(j<img_channels)
			{
				pixel.val[j] = LSB_BIT( (int)pixel.val[j],  ((byte >> i) & 1) );

				i--;

				if(i < 0)
				{
					break;
				}

				j++;
			}

			cvSet2D(img, pixelmap[index].x_coord, pixelmap[index].y_coord, pixel);

			pixelmap[index].used = TRUE;
		}

		written_bytes++;

	}
	DEBUG( ("done\n") );


	printf("%d Bytes written to image\n", written_bytes);


	return written_bytes;
}