Esempio n. 1
0
File: main.c Progetto: fevrite/lmp9
int main(int argc, char ** argv) {
	int res;
	Matrix * A = readFromFile(argv[1]);
	Matrix * b = readFromFile(argv[2]);
	Matrix * x;

	if (A == NULL) return -1;
	if (b == NULL) return -2;
	printToScreen(A);
	printToScreen(b);

	res = eliminate(A,b);
	x = createMatrix(b->r, 1);
	if (x != NULL) {
		res = backsubst(x,A,b);

		printToScreen(x);
	  freeMatrix(x);
	} else {
					fprintf(stderr,"Błąd! Nie mogłem utworzyć wektora wynikowego x.\n");
	}

	freeMatrix(A);
	freeMatrix(b);

	return 0;
}
static void android_server_BatteryService_update(JNIEnv* env, jobject obj)
{
    setBooleanField(env, obj, ACO, gFieldIds.mAcOnline);
    setBooleanField(env, obj, USBO, gFieldIds.mUsbOnline);
    setBooleanField(env, obj, BPRS, gFieldIds.mBatteryPresent);
    
    setPercentageField(env, obj, BCAP, gFieldIds.mBatteryLevel);
    setVoltageField(env, obj, BVOL, gFieldIds.mBatteryVoltage);
    setIntField(env, obj, BTMP, gFieldIds.mBatteryTemperature);
    
    const int SIZE = 128;
    char buf[SIZE];
    
    if (readFromFile(BSTS, buf, SIZE) > 0)
        env->SetIntField(obj, gFieldIds.mBatteryStatus, getBatteryStatus(buf));
    else
        env->SetIntField(obj, gFieldIds.mBatteryStatus,
                         gConstants.statusUnknown);
    
    if (readFromFile(BHTH, buf, SIZE) > 0)
        env->SetIntField(obj, gFieldIds.mBatteryHealth, getBatteryHealth(buf));

    if (readFromFile(BTECH, buf, SIZE) > 0)
        env->SetObjectField(obj, gFieldIds.mBatteryTechnology, env->NewStringUTF(buf));
}
static void android_server_BatteryService_update(JNIEnv* env, jobject obj)
{
    setBooleanField(env, obj, gPaths.acOnlinePath, gFieldIds.mAcOnline);
    setBooleanField(env, obj, gPaths.usbOnlinePath, gFieldIds.mUsbOnline);
    setBooleanField(env, obj, gPaths.batteryPresentPath, gFieldIds.mBatteryPresent);
    
    setIntField(env, obj, gPaths.batteryCapacityPath, gFieldIds.mBatteryLevel);
    setVoltageField(env, obj, gPaths.batteryVoltagePath, gFieldIds.mBatteryVoltage);
    setIntField(env, obj, gPaths.batteryTemperaturePath, gFieldIds.mBatteryTemperature);
    
    const int SIZE = 128;
    char buf[SIZE];
    
    if (readFromFile(gPaths.batteryStatusPath, buf, SIZE) > 0)
        env->SetIntField(obj, gFieldIds.mBatteryStatus, getBatteryStatus(buf));
    else
        env->SetIntField(obj, gFieldIds.mBatteryStatus,
                         gConstants.statusUnknown);
    
    if (readFromFile(gPaths.batteryHealthPath, buf, SIZE) > 0)
        env->SetIntField(obj, gFieldIds.mBatteryHealth, getBatteryHealth(buf));

    if (readFromFile(gPaths.batteryTechnologyPath, buf, SIZE) > 0)
        env->SetObjectField(obj, gFieldIds.mBatteryTechnology, env->NewStringUTF(buf));
}
Esempio n. 4
0
void handleESOptions(ES es, std::map<std::string, std::string> config) {
  if (config.count("setup") > 0) {
    typename ES::KeyPair p = es.Setup(std::stoi(config["base_security_parameter"]));
    writeToFile(p.sk, config["secret_key_file_name"]);
    writeToFile(p.pk, config["public_key_file_name"]);
  }

  if (config.count("encrypt") > 0) {
    typename ES::PublicKey pk;
    readFromFile(pk, config["public_key_file_name"]);
    typename ES::PlainText msg;
    readFromFile(msg, config["plain_text_file_name"]);

    typename ES::CipherText ct = es.Encrypt(pk, msg);
    writeToFile(ct, config["cipher_text_file_name"]);
  }

  if (config.count("decrypt") > 0) {
    typename ES::SecretKey sk;
    readFromFile(sk, config["secret_key_file_name"]);
    typename ES::CipherText ct;
    readFromFile(ct, config["cipher_text_file_name"]);

    typename ES::PlainText pt = es.Decrypt(sk, ct);
    writeToFile(pt, config["plain_text_file_name"]);
  }
}
void raedCipherSpec(const char * filePath, const char * userName , char * cipherSpec){
	
	FILE *file = fopen(filePath, "rt");

	if(file == NULL || userName == NULL){
		perror(filePath);
		return -1;
	}
	
	char name[512];
	char cipherss[20];
	int userChar;
	int exit = 0;
	
	do{
		userChar = readFromFile(file , name);
		readFromFile(file , cipherss);
		
		if(userChar <= 0)
			return;
		
		name[userChar] = '\0';

		if(strncmp(name , userName , strlen(userName)) == 0)
		{
		cipherSpec[0] = cipherss[0];
		exit = 1;			
		}
		
	}while(exit == 0);
	
	fclose(file);	
	
}
Esempio n. 6
0
    filepoint findLeaf(const KeyType &key){
        Tnode<KeyType> tempnode;
        filepoint nextp,temp;
        int keyindex;
        int keynum;
        if (rootloc != 0){
            tempnode = readFromFile(rootloc);
            temp = rootloc;
//            std::cout<<"this filepoint"<<temp<<std::endl;
//            tempnode.printData ();
//            std::cout<<"_________find______"<<std::endl;
//            tempnode.printData ();
//            std::cout<<"___________________"<<std::endl;
            while (tempnode.getLeaf ()==0){
//                std::cout<<"this filepoint"<<temp<<std::endl;
//                tempnode.printData ();
                keyindex = tempnode.getKeyIndex (key);
                keynum = tempnode.getKeyNum ();
                nextp = tempnode.getChild (keyindex);
                father[nextp]=temp;
                tempnode = readFromFile (nextp);
                temp = nextp;
            }
            return temp;
        }
        //else std::cout<<"error in index findleaf"<<std::endl;
        return 0;
    }
Esempio n. 7
0
int test_store_restore(TestData* testdata){
	MotionDetect md;
	test_bool(initMotionDetect(&md, &testdata->fi, "test") == VS_OK);
	test_bool(configureMotionDetect(&md)== VS_OK);

	LocalMotions lms;
	int i;
	for(i=0; i<2; i++){
		test_bool(motionDetection(&md, &lms,&testdata->frames[i])== VS_OK);
		if (i==0) vs_vector_del(&lms);
	}

	FILE* f = fopen("lmtest","w");
	storeLocalmotions(f,&lms);
	fclose(f);
	f = fopen("lmtest","r");
	LocalMotions test = restoreLocalmotions(f);
	fclose(f);
	storeLocalmotions(stderr,&test);
	compare_localmotions(&lms,&test);
	fprintf(stderr,"\n** LM and LMS OKAY\n");

	f = fopen("lmstest","w");
	md.frameNum=1;
	prepareFile(&md,f);
	writeToFile(&md,f,&lms);
	md.frameNum=2;
	writeToFile(&md,f,&test);
	fclose(f);

	f = fopen("lmstest","r");
	test_bool(readFileVersion(f)==1);
	LocalMotions read1;
	test_bool(readFromFile(f,&read1)==1);
	compare_localmotions(&lms,&read1);
	LocalMotions read2;
	test_bool(readFromFile(f,&read2)==2);
	compare_localmotions(&test,&read2);
	fclose(f);
	fprintf(stderr,"** Reading file stepwise OKAY\n");
	vs_vector_del(&read1);
	vs_vector_del(&read2);
	vs_vector_del(&test);
	vs_vector_del(&lms);

	f = fopen("lmstest","r");
	ManyLocalMotions mlms;
	test_bool(readLocalMotionsFile(f,&mlms)==VS_OK);
	test_bool(vs_vector_size(&mlms)==2);
	fprintf(stderr,"** Entire file routine OKAY\n\n");

	for(i=0; i< vs_vector_size(&mlms); i++){
		if(MLMGet(&mlms,i))
			vs_vector_del(MLMGet(&mlms,i));
	}
	vs_vector_del(&mlms);

	return 1;
}
Esempio n. 8
0
GIFError CGIFFile::readHeader(void)
{
	GIFError status;

	///////////////////////////////
	//	Read the GIF signature.  //
	///////////////////////////////

	// Read in the GIF file signature that identifies the file as a GIF
	// file.  This will consist of one of the two 6-byte strings "GIF87a"
	// or "GIF89a", so an extra entry is required to NULL-terminate the
	// data to make it a proper string.
	char signature[7];
	status = readFromFile(signature, 6);
	if (status != GIF_Success)
		return status;
	signature[6] = '\0';
	strlwr(signature);

	// If neither of the valid signatures is present, then this is
	// not a recognized version of a GIF file.
	if (strcmp(signature, "gif87a") && strcmp(signature, "gif89a"))
		return GIF_FileIsNotGIF;


	///////////////////////////////////
	//	Read the screen descriptor.  //
	///////////////////////////////////

	// Read the image property data from the file header.
	GIFScreenDescriptor screen;
	status = readFromFile(&screen, sizeof(screen));
	if (status != GIF_Success)
		return status;

	// Calculate the color resolution of the global color table.
	// This tells the number of 3-byte entries in that table.
	int colorResolution = ((screen.PackedFields >> 4) & 0x07) + 1;
	if (colorResolution < 2)
		colorResolution = 2;

	// Check to see if a global color table is present in the file.
	// If so, then allocate a color table and read the data from
	// the file.  This global table will be used by all images that
	// do not have a local color table defined.
	if (screen.PackedFields & GIFGlobalMapPresent) {
		DWORD bitShift = (screen.PackedFields & 0x07) + 1;
		m_GlobalColorMapEntryCount = 1 << bitShift;
		status = readFromFile(m_GlobalColorMap, 3 * m_GlobalColorMapEntryCount);
		if (status != GIF_Success)
			return status;
	}

	// Record the full dimensions of the images in the file.
	m_ImageWidth  = screen.Width;
	m_ImageHeight = screen.Height;

	return GIF_Success;
}
Esempio n. 9
0
void highscores () {
	FILE *list,*list1;
	highscore_t *highscores, *highscores1;
	int input, i=1;
	int row=25, rowTemp=row+55, columnTemp=22, column=22;

	backgroundImage (TEXT);

	positionCursor(43,11);
	printf ("  _    _ _____ _____ _    _    _____  _____ ____  _____  ______ \n");
	positionCursor(43,12);
	printf (" | |  | |_   _/ ____| |  | |  / ____|/ ____/ __ \\|  __ \\|  ____|\n");
	positionCursor(43,13);
	printf (" | |__| | | || |  __| |__| | | (___ | |   | |  | | |__) | |__   \n");
	positionCursor(43,14);
	printf (" |  __  | | || | |_ |  __  |  \\___ \\| |   | |  | |  _  /|  __|  \n");
	positionCursor(43,15);
	printf (" | |  | |_| || |__| | |  | |  ____) | |___| |__| | | \\ \\| |____ \n");
	positionCursor(43,16);
	printf (" |_|  |_|_____\\_____|_|  |_| |_____/ \\_____\\____/|_|  \\_\\______|\n");
	positionCursor(43,17);
	printf ("                                                                ");

	positionCursor (35,19);
	printf ("REAL TIME");
	positionCursor (100,19);
	printf ("POSITIONAL");

	list = fopen ("highscore.bin","rb");
	highscores = readFromFile (list);
	list1 = fopen ("highscore1.bin","rb");
	highscores1 = readFromFile (list1);

	while (1) {
		if((highscores==null)||(highscores1==null)) break;
		positionCursor (row,column);
		printf ("%d. %.2f %s | ", i, highscores->score, highscores->name);
		printf(ctime(&(highscores->date)));
		
		positionCursor (rowTemp,column);
		column+=2;
		printf ("%d. %.2f %s | ", i++, highscores1->score, highscores1->name);
		printf(ctime(&(highscores1->date)));
		

		highscores=highscores->succ;
		highscores1=highscores1->succ;
		
	}
	dealocateList(highscores);
	fclose(list);
	fclose(list1);

	while (1) {
		input=controls(_getch());
		if ((input==PAUSE)||(input==EXIT)) break;
	}

}
Esempio n. 10
0
/**
 * Create Diffie-Hellman parameters and save them to files.
 * Compute the shared secret and computed key from the received other public key.
 * Save shared secret and computed key to file.
 */
bool replyToFirstMessage() {
    cout << "Reply To First Message" << endl;

    // Split received file into separate files
    vector<string> outputFiles;
    outputFiles.push_back(OTHER_FIRST_MESSAGE_RANDOM_NUMBER);
    outputFiles.push_back(OTHER_PUBLIC_KEY_FILE_NAME);
    vector<int> bytesPerFile;
    bytesPerFile.push_back(RANDOM_NUMBER_SIZE);
    splitFile(FIRST_MESSAGE_FILE_NAME, outputFiles, bytesPerFile);

    // Read in received Diffie-Hellman public key from file
    SecByteBlock otherPublicKey;
    readFromFile(OTHER_PUBLIC_KEY_FILE_NAME, otherPublicKey);

    // Read in received random number from file
    SecByteBlock otherFirstMessageRandomNumber;
    readFromFile(OTHER_FIRST_MESSAGE_RANDOM_NUMBER, otherFirstMessageRandomNumber);

    // Prepare Diffie-Hellman parameters
    SecByteBlock publicKey;
    SecByteBlock privateKey;
    generateDiffieHellmanParameters(publicKey, privateKey);

    // Write public key and private key to files
    writeToFile(PRIVATE_KEY_FILE_NAME, privateKey);
    writeToFile(PUBLIC_KEY_FILE_NAME, publicKey);

    // Compute shared secret
    SecByteBlock sharedSecret;
    if (!diffieHellmanSharedSecretAgreement(sharedSecret, otherPublicKey, privateKey)) {
        cerr << "Security Error in replyToFirstMessage. Diffie-Hellman shared secret could not be agreed to." << endl;
        return false;
    }

    // Compute key from shared secret
    SecByteBlock key;
    generateSymmetricKeyFromSharedSecret(key, sharedSecret);

    // Write shared secret and computed key to file
    writeToFile(SHARED_SECRET_FILE_NAME, sharedSecret);
    writeToFile(COMPUTED_KEY_FILE_NAME, key);

    // Generate random number
    SecByteBlock firstMessageRandomNumber;
    generateRandomNumber(firstMessageRandomNumber, RANDOM_NUMBER_SIZE);

    // Write random number to file
    writeToFile(FIRST_MESSAGE_RANDOM_NUMBER_FILE_NAME, firstMessageRandomNumber);

    vector<string> inputFileNames;
    inputFileNames.push_back(FIRST_MESSAGE_RANDOM_NUMBER_FILE_NAME);
    inputFileNames.push_back(PUBLIC_KEY_FILE_NAME);
    combineFiles(inputFileNames, FIRST_MESSAGE_REPLY_FILE_NAME);

    return true;
}
Esempio n. 11
0
GIFError CGIFFile::readBlock(BYTE *buffer, BYTE &blockSize)
{
	GIFError status = readFromFile(&blockSize, 1);
	if (status != GIF_Success)
		return status;

	if (blockSize)
		status = readFromFile(buffer, blockSize);

	return status;
}
Esempio n. 12
0
// Send List of users from login file to asking client
void ServerManager::getListUsers(User *client)
{
	int numOfusers = 0;
	numOfusers = numOfUsersFromFile();

	client->writeCommand(LIST_USERS);
	client->writeCommand(numOfusers -1);

	if (client != NULL)
		readFromFile(client);
	else
		readFromFile(NULL);

}
Esempio n. 13
0
int isInCipherSpec(const char * filePath, const char * cipherSpec){
	FILE *file = fopen(filePath, "rt");

	if(file == NULL){
		perror(filePath);
		return -1;
	}
	
	char cipherss[20];
	int exit = 0;
	
	do{
		int read = readFromFile(file , cipherss);
		
		if(read <= 0)
			return - 1;

		if(cipherss[0] == cipherSpec[0])
			return 1;
		
	}while(exit == 0);
	
	fclose(file);	
	
}
Esempio n. 14
0
int main()
{
    int N = _5000;

    char ** content = readFromFile(N);
    //printContentToConsole(content,N);

    initHashTable(N);
    int i, aux;
    int maxColl = 0;
    nrOfResize = 0;
    float avgColl= 1;

    for (i=0; i<N; i++)
    {
        if ((i % 20) ==0)
            printf("\nElement Collisions FillFactor\n\n");
        aux = insertElement(*(content+i));
        printf("%7d %10d", i, aux);
        if (maxColl < aux)
            maxColl = aux;
        printf(" %8.2f%% \n", 100*getFillFactor());
        avgColl=(float)((((float)(avgColl)*i)+(float)aux)/(float)(i+1));


    }
    printf("\nNumber of resizes: %d\n", nrOfResize);
    printf("\nMaximal number of collisions: %d\n", maxColl);
    printf("\nAverage number of collisions: %f\n", avgColl);
    return 0;
}
Esempio n. 15
0
int main(int argc, char** argv) {
    int maximumValue = 0, maximumWeight = 0, noOfItems = 0;
    int binaryString[MAXITEMS], optimalList[MAXITEMS];
    int i = 0;
    item items[MAXITEMS];

    //if a file has been specified.
    if (argc > 1) {
        readFromFile(argv[1], &maximumWeight, &noOfItems, items);
    }
        //no file specified.
    else {
        readFromConsole(&maximumWeight, &noOfItems, items);
    }

    //call the recursive function to enumerate all possibilities.
    enumItemSubset(0, binaryString, noOfItems, items, maximumWeight, &maximumValue, optimalList);

    //Print the output.
    printf("%d", maximumValue);
    for (i = 0; i < noOfItems; i++) {
        if (optimalList[i]) {
            printf(" %s", items[i].name);
        }
    }

    return (EXIT_SUCCESS);
}
Esempio n. 16
0
void ResourceManager::loadResource( string_hash resourceId )
{
	const uint32_t index = _resources.find( resourceId.hash() );

	if( index == ResourceMap::INVALID )
		return;

	const string_hash typeId = _resources.get_value( index )->typeId;

	intrusive_node<ResourceFilter>* node = _filters.begin();
    for( ; node != _filters.end(); node = node->next() )
    {
        if( *(node->parent()) == typeId )
        {
        	const string256 filePath = _path + _resources.get_value(index)->filename;
        	const uint32_t resourceSize  = crap::fileSize( filePath.c_str() );


			file_t* resourceFile = openFile( filePath.c_str(), CRAP_FILE_READBINARY );

        	CRAP_ASSERT( ASSERT_BREAK, resourceFile != 0, "Resourcefile not found" );

        	pointer_t<void> memory = _allocator.allocate( resourceSize, 4 );

        	readFromFile( resourceFile, memory, resourceSize );
        	node->parent()->import( resourceId, memory, resourceSize, _system );

        	_allocator.deallocate( memory.as_void );
        	closeFile( resourceFile );
        }
    }
}
Esempio n. 17
0
/**
 * Decrypt received facial recognition parameters.
 * Encrypt facial recognition parameters.
 */
bool replyToThirdMessage() {
    cout << "Reply To Third Message" << endl;
    // Read session key from file
    SecByteBlock key;
    readFromFile(COMPUTED_KEY_FILE_NAME, key);

    // Read in the current initialization vector from file
    byte curIv[AES::BLOCKSIZE];
    // TODO: actually read it in
    // Set to 0 for now
    memset(curIv, 0, AES::BLOCKSIZE);

    // Decrypt received facial recognition params
    if (!decryptFile(THIRD_MESSAGE_FILE_NAME, 
            RECEIVED_FACIAL_RECOGNITION_FILE_NAME,
            key, curIv)) {
        cerr << "Security Error in replyToThirdMessage. MAC could not be verified." << endl;
        return false;
    }

    // Encrypt facial recognition params
    encryptFile(FACIAL_RECOGNITION_FILE_NAME, 
            THIRD_MESSAGE_REPLY_FILE_NAME, 
            key, curIv);
    return true;
}
Esempio n. 18
0
int main() {
	std::vector<measurement> readings, withinOne, notWithinOne;
	stats out_stats;

	//Get information from file
	readFromFile("TestData.txt", readings);

	out_stats.mean = calculateMean(readings);
	out_stats.standard_dev = calculateStdDev(readings);
	out_stats.totalmeasurements = getTotalMeasurements(readings);

	isWithinOne(readings, withinOne, notWithinOne, out_stats.mean, out_stats.standard_dev);

	out_stats.totalMeasurements_withinOneStdDev = withinOne.size();
	out_stats.totalMeasurements_outsideOneStdDev = notWithinOne.size();

	readings.clear(); //no longer need readings

	sort(withinOne);
	sort(notWithinOne);
	
	print_to_file(withinOne, notWithinOne, out_stats);

	withinOne.clear();
	notWithinOne.clear();

	return 0;
}
Esempio n. 19
0
uint ModelData::addOutput( 	const String& output, const String& diffs_output, const uint dim,
							const String& colInd, const String& rowPtr	){


	Vector colIndV = readFromFile( colInd.getName() );
	Vector rowPtrV = readFromFile( rowPtr.getName() );
	if( rowPtrV.getDim() != (dim+1) ) {
		return ACADOERROR( RET_INVALID_OPTION );
	}
	colInd_outputs.push_back( colIndV );
	rowPtr_outputs.push_back( rowPtrV );

	addOutput( output, diffs_output, dim );

    return addOutput( output, diffs_output, dim );
}
MovieCollection::MovieCollection(const MovieCollection &mc)
{
	m_dirty = mc.m_dirty;
	m_collectionName = mc.m_collectionName;
	m_xmlFilePath = mc.m_xmlFilePath;
	readFromFile();
}
Esempio n. 21
0
 std::list<filepoint> findlesseq(const KeyType &key){
     Tnode<KeyType> tempnode;
     filepoint temp;
     std::list<filepoint> ans;
     if (firstloc ==0){
         return ans;
     }
     temp = firstloc;
     ans.clear();
     if (temp==0) return ans;
     while (temp!=0){
         tempnode = readFromFile (temp);
         if (tempnode.getLeaf ()==0) {
             //std::cout<<"wrong in findless"<<std::endl;
             return ans;
         }
         int kid = tempnode.getKeyIndex (key);
         for (int i=0;i<kid;++i) ans.push_back (tempnode.getChild (i));
         if (kid>0 && kid == tempnode.getKeyNum ())
             temp = tempnode.getChild (kid);
         else
             return ans;
     }
     return ans;
 }
Esempio n. 22
0
BatteryMonitor::PowerSupplyType BatteryMonitor::readPowerSupplyType(const String8& path) {
    const int SIZE = 128;
    char buf[SIZE];
    int length = readFromFile(path, buf, SIZE);
    BatteryMonitor::PowerSupplyType ret;
    struct sysfsStringEnumMap supplyTypeMap[] = {
        { "Unknown", ANDROID_POWER_SUPPLY_TYPE_UNKNOWN },
        { "Battery", ANDROID_POWER_SUPPLY_TYPE_BATTERY },
        { "UPS", ANDROID_POWER_SUPPLY_TYPE_AC },
        { "Mains", ANDROID_POWER_SUPPLY_TYPE_AC },
        { "USB", ANDROID_POWER_SUPPLY_TYPE_USB },
        { "USB_DCP", ANDROID_POWER_SUPPLY_TYPE_AC },
        { "USB_CDP", ANDROID_POWER_SUPPLY_TYPE_AC },
        { "USB_ACA", ANDROID_POWER_SUPPLY_TYPE_AC },
        { "Wireless", ANDROID_POWER_SUPPLY_TYPE_WIRELESS },
        { NULL, 0 },
    };

    if (length <= 0)
        return ANDROID_POWER_SUPPLY_TYPE_UNKNOWN;

    ret = (BatteryMonitor::PowerSupplyType)mapSysfsString(buf, supplyTypeMap);
    if (ret < 0)
        ret = ANDROID_POWER_SUPPLY_TYPE_UNKNOWN;

    return ret;
}
Esempio n. 23
0
unsigned int GyroscopeAdaptor::interval() const
{
    if (mode() == SysfsAdaptor::IntervalMode)
        return SysfsAdaptor::interval();
    QByteArray byteArray = readFromFile(dataRatePath_);
    return byteArray.size() > 0 ? byteArray.toInt() : 0;
}
Esempio n. 24
0
void FileStream::read(char* buffer, int length)
{
    ASSERT(!isMainThread());

    if (!isHandleValid(m_handle)) {
        m_client->didFail(NOT_READABLE_ERR);
        return;
    }

    if (m_bytesProcessed >= m_totalBytesToRead) {
        m_client->didFinish();
        return;
    }

    long long remaining = m_totalBytesToRead - m_bytesProcessed;
    int bytesToRead = (remaining < length) ? static_cast<int>(remaining) : length;
    int bytesRead = readFromFile(m_handle, buffer, bytesToRead);
    if (bytesRead < 0) {
        m_client->didFail(NOT_READABLE_ERR);
        return;
    }

    if (!bytesRead) {
        m_client->didFinish();
        return;
    }

    m_bytesProcessed += bytesRead;
    m_client->didRead(buffer, bytesRead);
}
int main(int argc, char *argv[])
{
    struct person per;
    per.next = NULL;
    struct person book;
    book.next = NULL;

    head = &book;
    tail = &book;
    FILE *file;

    file = fopen(argv[1], "r");
    if (file == NULL){
        printf("new file created \n");
        file = fopen(argv[1], "w");
    }else{
        readFromFile(file, &per);
    }

    struct person *iter = head;

    while ((iter->next) != NULL){
        printf("%d", iter->id);
    }
    char *command;

    while(1){
        scanf("%s", command);
        if(!strcmp(command, "exit")){
           break;
        }
    }
    return 0;
}
Esempio n. 26
0
PlayList::PlayList(Player *player, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PlayList)
{
    ui->setupUi(this);
    curIndex = 0;
    lengthFilter = 0;
    this->player = player;
    ui->playListTable->horizontalHeader()->setStretchLastSection(true);//自动设置最后一列宽度
    this->setWindowFlags(Qt::WindowTitleHint | Qt::CustomizeWindowHint);
    this->setFixedSize(this->width(), this->height());

    //“查找”文本框,绑定回车键到“查找”按钮
    connect(ui->searchEdit, SIGNAL(returnPressed()), this, SLOT(on_searchButton_clicked()));

    readFromFile(QCoreApplication::applicationDirPath() + "/PlayList.sdpl");

    //搜索功能部分的动画
    //搜索条
    finderAnimation = new QPropertyAnimation(ui->finderFlame, "geometry");
    finderAnimation->setEasingCurve(QEasingCurve::OutCirc);
    finderAnimation->setDuration(600);
    finderAnimation->setStartValue(QRect(331, 330, 331, 31));
    finderAnimation->setEndValue(QRect(0, 330, 331, 31));
    //播放列表
    playListAnimation = new QPropertyAnimation(ui->playListTable, "geometry");
    playListAnimation->setDuration(600);
    playListAnimation->setEasingCurve(QEasingCurve::OutCirc);
}
//-------
void SuperCollider::setup() {
    buses["bus1"] = new ofxSCBus();
    buses["bus2"] = new ofxSCBus();
    buses["bus3"] = new ofxSCBus();
    
    buffers["buf1"] = new ofxSCBuffer();

    control.setName("Sc3");
    

    string synthFile = "/Users/Gene/Code/openFrameworks/tools/SuperCollider/synths.scd";
    readFromFile("buffer", synthFile);
    readFromFile("event", synthFile);
    readFromFile("source", synthFile);
    readFromFile("modifier", synthFile);
}
//===================
//======= MAIN ======
//===================
int main(int argc, const char * argv[]) {
    //Create seed for  rand() "random" num generation
    srand((unsigned int)time(NULL));
    
    //Calls function to generate new directory, return name of dir
    char* myDirName = makeMyDir();
    //Returns a 'string array' of file names, pass in directory name.
    char** roomNames= generateRoomFiles(myDirName);
    //Input game info from file, pass in file names and directory name.
    readFromFile(roomNames,myDirName);
    //Main driver of game, after game information extracted
    middleEarthAdventure(myDirName);
    
    
    
    
    //FREE UP ALLOCATED MEMORY
    int freeIt;
    for(freeIt=0;freeIt<7; freeIt++)
    {free(roomNames[freeIt]);}
    free(roomNames);
    free(myDirName);
    //---

    return 0;
}
Esempio n. 29
0
BEGIN_NAMESPACE_QPOASES


/*
 *	r e a d O q p D i m e n s i o n s
 */
returnValue readOqpDimensions(	const char* path,
								int_t& nQP, int_t& nV, int_t& nC, int_t& nEC
								)
{
	/* 1) Setup file name where dimensions are stored. */
	char filename[MAX_STRING_LENGTH];
	snprintf( filename,MAX_STRING_LENGTH,"%sdims.oqp",path );

	/* 2) Load dimensions from file. */
	int_t dims[4];
	if ( readFromFile( dims,4,filename ) != SUCCESSFUL_RETURN )
		return THROWERROR( RET_UNABLE_TO_READ_FILE );

	nQP = dims[0];
	nV  = dims[1];
	nC  = dims[2];
	nEC = dims[3];


	/* consistency check */
	if ( ( nQP <= 0 ) || ( nV <= 0 ) || ( nC < 0 ) || ( nEC < 0 ) )
		return THROWERROR( RET_FILEDATA_INCONSISTENT );

	return SUCCESSFUL_RETURN;
}
Esempio n. 30
0
unsigned int Data::GetWord(unsigned int wordPosition)
{
	ifstream readFromFile("../TP3-H13/src - AT/Database.txt",ios::in);

    // Creating a string variable.
    std::string temp;

	int counter = 0;
    while(!readFromFile.eof()){ // I cant figure out what to add here so that the code will find and store the destination.
        getline(readFromFile, temp);
		if(counter == wordPosition)
			break;
		else
			counter++;
    }


	if(temp.length() > 0)
	{	
		wordLength = std::stoi(temp.substr(0, temp.find(" ")));
		word = temp.substr(temp.find(" ")+1, temp.length()-1);
		return wordLength;
	}

	return 0;
}