Exemple #1
0
 FOR_EACH (STD_VECTOR<Label*>::iterator, it, mLabels)
 {
     remove(*it);
     delete *it;
 }
	bool CFileSystem::Delete(const char* szPath, bool bRecursive)
	{
		BEHAVIAC_UNUSED_VAR(bRecursive);

		return remove(szPath) == 0;
	}
Exemple #3
0
void CodeDocument::deleteSection (const int start, const int end)
{
    remove (start, end, true);
}
Exemple #4
0
void
Checkpoint::updateCheckpointFiles(CheckpointFileNames file_struct)
{
  int ret = 0;          // return code for file operations

  // Update the list of stored files
  _file_names.push_back(file_struct);

  // Remove un-wanted files
  if (_file_names.size() > _num_files)
  {
    // Extract the filenames to be removed
    CheckpointFileNames delete_files = _file_names.front();

    // Remove these filenames from the list
    _file_names.pop_front();

    // Get thread and proc information
    processor_id_type proc_id = processor_id();

    // Delete checkpoint files (_mesh.cpr)

    if (proc_id == 0)
    {
      ret = remove(delete_files.checkpoint.c_str());
      if (ret != 0)
        mooseWarning("Error during the deletion of file '" << delete_files.checkpoint << "': " << ret);

      // Delete the system files (xdr and xdr.0000, ...)
      ret = remove(delete_files.system.c_str());
      if (ret != 0)
        mooseWarning("Error during the deletion of file '" << delete_files.system << "': " << ret);
    }

    {
      std::ostringstream oss;
      oss << delete_files.system
          << "." << std::setw(4)
          << std::setprecision(0)
          << std::setfill('0')
          << proc_id;
      ret = remove(oss.str().c_str());
      if (ret != 0)
        mooseWarning("Error during the deletion of file '" << oss.str().c_str() << "': " << ret);
    }

    unsigned int n_threads = libMesh::n_threads();

    // Remove material property files
    if (_material_property_storage.hasStatefulProperties() || _bnd_material_property_storage.hasStatefulProperties())
    {
      ret = remove(delete_files.material.c_str());
      if (ret != 0)
        mooseWarning("Error during the deletion of file '" << delete_files.material << "': " << ret);

      for (THREAD_ID tid = 0; tid < n_threads; tid++)
      {
        std::ostringstream oss;
        oss << delete_files.material << '-' << proc_id;
        if (n_threads > 1)
          oss << "-" << tid;
        ret = remove(oss.str().c_str());
        if (ret != 0)
          mooseWarning("Error during the deletion of file '" << oss.str().c_str() << "': " << ret);
      }
    }

    // Remove the restart files (rd)
    {
      for (THREAD_ID tid = 0; tid < n_threads; tid++)
      {
        std::ostringstream oss;
        oss << delete_files.restart << "-" << proc_id;
        if (n_threads > 1)
          oss << "-" << tid;
        ret = remove(oss.str().c_str());
        if (ret != 0)
          mooseWarning("Error during the deletion of file '" << oss.str().c_str() << "': " << ret);
      }
    }
  }
}
Exemple #5
0
bool test_udpc_share(){
  const char * arg0[] = {"server", NULL};
  const char *arg1[] = {"share", "[email protected]:a", "test share", NULL};
  const char * arg2[]= {"share","[email protected]:a","test share2","[email protected]:a", NULL};
  char test_code[5000];
  memset(test_code, 'a', sizeof(test_code));
  test_code[sizeof(test_code) - 1] = 0;
  iron_process server_proc, share_1_proc, share_2_proc;
  
  ASSERT(0 == iron_process_run("./server",arg0, &server_proc));  

  // setup dirs
  remove("test share/hello.txt");
  remove("test share/hello2.txt");
  remove("test share/hello3.txt");
  remove("test share");
  remove("test share2/hello.txt");
  remove("test share2/hello2.txt");
  remove("test share2/hello3.txt");
  remove("test share2");

  mkdir("test share/", 0777);
  write_string_to_file(test_code, "test share/hello.txt");
  write_string_to_file(test_code, "test share/hello2.txt");
  mkdir("test share2/", 0777);
  write_string_to_file(test_code, "test share2/hello3.txt");
  iron_usleep(100000);

  ASSERT(0 == iron_process_run("./share", arg1, &share_1_proc));
  iron_usleep(100000);
  ASSERT(0 == iron_process_run("./share", arg2, &share_2_proc));

  logd("Waiting for process %p\n", timestamp());
  logd("STATUS C2: %i\n", iron_process_get_status(share_2_proc));
  iron_process_wait(share_2_proc, 30000000);
  logd("end %p\n", timestamp());
  iron_process_status s_c2 = iron_process_get_status(share_2_proc);
  // Interrupt first then kill in case it did not work.
  kill(server_proc.pid, SIGINT);
  kill(share_1_proc.pid, SIGINT);
  kill(share_2_proc.pid, SIGINT);
  iron_usleep(10000);
  kill(server_proc.pid, SIGINT);
  kill(share_1_proc.pid, SIGINT);
  kill(share_2_proc.pid, SIGINT);
  iron_usleep(10000);
  kill(server_proc.pid, SIGKILL);
  kill(share_1_proc.pid, SIGKILL);
  kill(share_2_proc.pid, SIGKILL);
  iron_usleep(10000);
  iron_process_status s1 = iron_process_get_status(server_proc);
  iron_process_status s_c1 = iron_process_get_status(share_1_proc);
  logd("exit statuses: %i %i %i\n", s1, s_c1, s_c2);
  sync();
  char * file_content = read_file_to_string("test share2/hello.txt");
  char * file_content2 = read_file_to_string("test share2/hello2.txt");
  
  ASSERT(file_content != NULL && file_content2 != NULL);
  logd("l1: %i, l2: %i\n", strlen(test_code), strlen(file_content));
  ASSERT(strcmp(test_code, file_content) == 0);
  ASSERT(strcmp(test_code, file_content2) == 0);
  dealloc(file_content);
  dealloc(file_content2);
  ASSERT(s_c2 == IRON_PROCESS_EXITED);
  iron_usleep(30000); // wait for ports to reopen.
  return TEST_SUCCESS;
}
int
main (int argc, char *argv[]) 
{
  if (argc != 3)
    fail ("huge-file: Error, usage: %s min_max_size_in_bytes niter", argv[0]);
  /* The minimum "max file size" we tolerate. */
  long min_max_size = atol (argv[1]);
  int niter = atoi (argv[2]);
  int i;

  long initial_max_file_size = -1;

  char zeros[CHUNK_SIZE];
  char out_buf[CHUNK_SIZE];
  char in_buf[CHUNK_SIZE];
  char tmp_buf[CHUNK_SIZE];

  memset (zeros, 0, CHUNK_SIZE);
  random_bytes (out_buf, CHUNK_SIZE);

  for (i = 0; i < niter; i++)
  {
    int create_big = random_ulong () % 2;
    int sparse = random_ulong () % 2;
    //msg ("iter %i: create_big %i sparse %i", i, create_big, sparse);

    long bytes_written = 0;

    long init_size = (create_big ? min_max_size : 0);
    if (!create (file, init_size))
      fail ("Error, could not create (\"%s\", %li)", file, init_size);

    int fd = open (file);
    if (fd < 0)
      fail ("Error, open (%s, 0) gave fd %i\n", file, fd);

    if (sparse)
    {
      /* Make the file sparse and read prior to each write. */
      seek (fd, min_max_size);
      char c = 0;
      if (write (fd, &c, 1) != 1)
        fail ("Error, could not write file sparsely: offset %li\n", min_max_size);
      /* Now do a read-write sequence. Ensure every read returns nulls. */
      long offset = 0;
      while (1)
      {
        //msg ("read-write sequence: num %i offset %li", offset/CHUNK_SIZE, offset);
        /* Read and verify it's nulls. */
        seek (fd, offset); 
        long n_read = read (fd, in_buf, CHUNK_SIZE);
        if (n_read != CHUNK_SIZE && offset+CHUNK_SIZE < min_max_size)
          fail ("Error, read %li instead of %i and I'm not at the end of the file\n", n_read, CHUNK_SIZE);
        if (memcmp (in_buf, zeros, n_read))
        {
          printf ("Error, read something besides zeros between offset %li and %li\n", offset, offset + n_read);
          printf ("I expected:\n");
          print_buf (zeros, n_read);
          printf ("I read:\n");
          print_buf (in_buf, n_read);
          fail ("Error, see above.\n");
        }


        /* Write data. */
        seek (fd, offset); 
        long n_written = write (fd, out_buf, CHUNK_SIZE);
        bytes_written += n_written;

        int verify_after_write = random_ulong () % 2;
        if (verify_after_write)
        {
          seek (fd, offset);
          long n_read = read (fd, tmp_buf, CHUNK_SIZE);
          if (n_read != n_written)
            fail ("Error, verifying after write, and I read %li bytes after writing %li bytes\n", n_read, n_written);
          long j;
          for (j = 0; j < n_read; j++)
          {
            if (tmp_buf[j] != out_buf[j])
              fail ("Error, mismatch between write and subsequent read. Offset %li expected <%c> read <%c>\n", offset + j, out_buf[j], tmp_buf[j]);
          }
        }

        if (n_written != CHUNK_SIZE)
          break;

        offset += CHUNK_SIZE;
      }
    }
    else
    {
      /* Just write out the file until it fails. */
      seek (fd, 0);

      long offset = 0;
      while (1)
      {
        //msg ("write sequence: num %li offset %li", offset/CHUNK_SIZE, offset);
        long n_written = write (fd, out_buf, CHUNK_SIZE); 
        bytes_written += n_written;
        if (n_written != CHUNK_SIZE)
          break;
        offset += CHUNK_SIZE;
      }
      //msg ("Max file size: %li", bytes_written);
    }

    close (fd);
    if (!remove (file))
      fail ("Error, could not delete file %s", file);

    if (i == 0)
      initial_max_file_size = bytes_written;

    /* Must be at least min_max_size bytes. */
    if (bytes_written < min_max_size)
      fail ("Error, could only write %li < %li bytes", bytes_written, min_max_size);

    /* Should be the same number every time, whatever it is. */
    if (initial_max_file_size != bytes_written)
      fail ("Error, on the first iteration I was able to write a total of %li bytes. On this iteration I wrote %li bytes. Why do these differ?", initial_max_file_size, bytes_written);

  }

  return 0;
}
Exemple #7
0
void HandleClientMsg(SSL_CLIENT_DATA* ssl_data, int epollfd)
{
	if(!ssl_data)
		return;
	SSL *ssl = ssl_data->ssl;
	char buffer[BUFF_LEN];
	int recvLen;
	bzero(buffer, BUFF_LEN);
	recvLen = SSL_recv(ssl, buffer, BUFF_LEN);
	if(recvLen <= 0 || strncmp(buffer, "quit", 4)==0)
	{
		printf("client quit!\n");
		SSL_Client_Leave(ssl_data, epollfd);
		return;
	}

	/*Parse the user cert request*/
	cJSON *root = cJSON_Parse(buffer);
	if(!root)	
	{
		HandleError(ssl, "JSON parse error!");
		goto end;
	}

	cJSON *child = root->child, *cmd=NULL, *attr=NULL;
	while(child)
	{
		if(0==strcmp(child->string, "cmd"))
			cmd = child;
		else if(0==strcmp(child->string, "attr"))
			attr = child;
		
		child = child->next;
	}

	printf("Receive from client %d: %s\n", SSL_get_fd(ssl_data->ssl), buffer);
	if(0==strcmp(cmd->valuestring, "get_cert"))
	{
		char *certFile = ProduceNewCertForUser(attr);	
		printf("certfile:%s;\n", certFile);
		fflush(NULL);
		
		/*Generate the response text*/
		char *resp = NULL;
		FILE *file = fopen(certFile, "r");
		if(!file)
		{
			HandleError(ssl, "Certificate generate failed with unknown error!\n");
		}else{
			fseek(file, 0L, SEEK_END);
			if(0==ftell(file))
			{
				HandleError(ssl, "Certificate generate failed with unknown error!\n");
				fclose(file);
				remove(certFile);
			}else{
				/*Calculate. Remove all the path prefix, leave the pure file name*/
				char *fileName = certFile, *ret=NULL;
				ret = strtok(certFile, "/");
				while(ret)
				{
					fileName = ret;
					ret = strtok(NULL, "/");
				}
				cJSON *resp_json = cJSON_CreateObject();
				cJSON_AddStringToObject(resp_json, "cmd", "sending_cert_next");
				cJSON *attr = cJSON_CreateObject();
				cJSON_AddItemToObject(resp_json, "attr", attr);
				cJSON_AddStringToObject(attr, "filename", fileName);
				char *resp = cJSON_Print(resp_json);
				cJSON_Delete(resp_json);
				SSL_send(ssl, resp, strlen(resp));
				free(resp);
				/*Next we must send the cert file to the client*/
				rewind(file);
				char buffer[512]={0};
				int len = 0, sendLen=0;
				while(!feof(file))
				{
					printf("Sending cert....\n");
					len = fread(buffer, sizeof(char), 511, file);
					if(len<=0)
						break;
					buffer[len] = '\0';
					sendLen = SSL_send(ssl, buffer, len);
					if(sendLen<len)
						break;
				}
				SSL_send(ssl, "!@done*#", 8);
				fclose(file);
			}
		}
		
		free(certFile);
	}else if(0==strcmp(cmd->valuestring, "pubkey_query"))
	{
		/*get the username*/
		char *username = NULL;
		if(0==strcmp(attr->child->string, "username"))
			username = attr->child->valuestring;

		if(!username)
		{
			HandleError(ssl, "You must specify the user name!");
			return;
		}
		/*Generate the response text*/
		char certFile[512];
		strcpy(certFile, "certs/client/");
		strcat(certFile, username);
		strcat(certFile, "Pub.pem");
		char *resp = NULL;
		FILE *file = fopen(certFile, "r");
		if(!file)
		{
			HandleError(ssl, "your requested file not exists!\n");
		}else{
			fseek(file, 0L, SEEK_END);
			if(0==ftell(file))
			{
				HandleError(ssl, "your requested file not exists!\n");
				fclose(file);
				remove(certFile);
			}else{
				/*Calculate. Remove all the path prefix, leave the pure file name*/
				char *fileName = basename(certFile), *ret=NULL;
				
				cJSON *resp_json = cJSON_CreateObject();
				cJSON_AddStringToObject(resp_json, "cmd", "sending_pubkey_next");
				cJSON *attr = cJSON_CreateObject();
				cJSON_AddItemToObject(resp_json, "attr", attr);
				cJSON_AddStringToObject(attr, "filename", fileName);
				char *resp = cJSON_Print(resp_json);
				cJSON_Delete(resp_json);
				SSL_send(ssl, resp, strlen(resp));
				free(resp);
				/*Next we must send the cert file to the client*/
				rewind(file);
				char buffer[512]={0};
				int len = 0, sendLen=0;
				while(!feof(file))
				{
					printf("Sending public key....\n");
					len = fread(buffer, sizeof(char), 511, file);
					if(len<=0)
						break;
					buffer[len] = '\0';
					sendLen = SSL_send(ssl, buffer, len);
					if(sendLen<len)
						break;
				}
				SSL_send(ssl, "!@done*#", 8);
				printf("Done.\n");
				fclose(file);
			}
		}
		
	}

end:
	cJSON_Delete(root);
}
/*****************************************************************
* int initialize_cape()
* sets up necessary hardware and software
* should be the first thing your program calls
*****************************************************************/
int initialize_cape(){
	FILE *fd; 		
	printf("\n");

	// check if another project was using resources
	// kill that process cleanly with sigint if so
	#ifdef DEBUG
		printf("checking for existing PID_FILE\n");
	#endif
	fd = fopen(PID_FILE, "r");
	if (fd != NULL) {
		int old_pid;
		fscanf(fd,"%d", &old_pid);
		if(old_pid != 0){
			printf("warning, shutting down existing robotics project\n");
			kill((pid_t)old_pid, SIGINT);
			sleep(1);
		}
		// close and delete the old file
		fclose(fd);
		remove(PID_FILE);
	}
	
	// create new pid file with process id
	#ifdef DEBUG
		printf("opening PID_FILE\n");
	#endif
	fd = fopen(PID_FILE, "ab+");
	if (fd < 0) {
		printf("\n error opening PID_FILE for writing\n");
		return -1;
	}
	pid_t current_pid = getpid();
	printf("Current Process ID: %d\n", (int)current_pid);
	fprintf(fd,"%d",(int)current_pid);
	fflush(fd);
	fclose(fd);
	
	// check the device tree overlay is actually loaded
	if (is_cape_loaded() != 1){
		printf("ERROR: Device tree overlay not loaded by cape manager\n");
		return -1;
	}
	
	// initialize mmap io libs
	printf("Initializing GPIO\n");
	if(initialize_gpio()){
		printf("mmap_gpio_adc.c failed to initialize gpio\n");
		return -1;
	}
	//export all GPIO output pins
	gpio_export(RED_LED);
	gpio_set_dir(RED_LED, OUTPUT_PIN);
	gpio_export(GRN_LED);
	gpio_set_dir(GRN_LED, OUTPUT_PIN);
	gpio_export(MDIR1A);
	gpio_set_dir(MDIR1A, OUTPUT_PIN);
	gpio_export(MDIR1B);
	gpio_set_dir(MDIR1B, OUTPUT_PIN);
	gpio_export(MDIR2A);
	gpio_set_dir(MDIR2A, OUTPUT_PIN);
	gpio_export(MDIR2B);
	gpio_set_dir(MDIR2B, OUTPUT_PIN);
	gpio_export(MDIR3A);
	gpio_set_dir(MDIR3A, OUTPUT_PIN);
	gpio_export(MDIR3B);
	gpio_set_dir(MDIR3B, OUTPUT_PIN);
	gpio_export(MDIR4A);
	gpio_set_dir(MDIR4A, OUTPUT_PIN);
	gpio_export(MDIR4B);
	gpio_set_dir(MDIR4B, OUTPUT_PIN);
	gpio_export(MOT_STBY);
	gpio_set_dir(MOT_STBY, OUTPUT_PIN);
	gpio_export(PAIRING_PIN);
	gpio_set_dir(PAIRING_PIN, OUTPUT_PIN);
	gpio_export(SPI1_SS1_GPIO_PIN);
	gpio_set_dir(SPI1_SS1_GPIO_PIN, OUTPUT_PIN);
	gpio_export(SPI1_SS2_GPIO_PIN);
	gpio_set_dir(SPI1_SS2_GPIO_PIN, OUTPUT_PIN);
	gpio_export(INTERRUPT_PIN);
	gpio_set_dir(INTERRUPT_PIN, INPUT_PIN);
	gpio_export(SERVO_PWR);
	gpio_set_dir(SERVO_PWR, OUTPUT_PIN);
	
	printf("Initializing ADC\n");
	if(initialize_adc()){
		printf("mmap_gpio_adc.c failed to initialize adc\n");
		return -1;
	}
	printf("Initializing eQEP\n");
	if(init_eqep(0)){
		printf("mmap_pwmss.c failed to initialize eQEP\n");
		return -1;
	}
	if(init_eqep(1)){
		printf("mmap_pwmss.c failed to initialize eQEP\n");
		return -1;
	}
	if(init_eqep(2)){
		printf("mmap_pwmss.c failed to initialize eQEP\n");
		return -1;
	}
	
	// setup pwm driver
	printf("Initializing PWM\n");
	if(simple_init_pwm(1,PWM_FREQ)){
		printf("simple_pwm.c failed to initialize PWMSS 0\n");
		return -1;
	}
	if(simple_init_pwm(2,PWM_FREQ)){
		printf("simple_pwm.c failed to initialize PWMSS 1\n");
		return -1;
	}
	
	// start some gpio pins at defaults
	deselect_spi1_slave(1);	
	deselect_spi1_slave(2);
	disable_motors();
	
	//set up function pointers for button press events
	printf("Initializing button interrupts\n");
	initialize_button_handlers();
	
	// Load binary into PRU
	printf("Initializing PRU\n");
	if(initialize_pru()){
		printf("ERROR: PRU init FAILED\n");
		return -1;
	}
	
	// Start Signal Handler
	printf("Initializing exit signal handler\n");
	signal(SIGINT, ctrl_c);	
	signal(SIGTERM, ctrl_c);	
	
	// Print current battery voltage
	printf("Battery Voltage: %2.2fV\n", get_battery_voltage());
	
	// all done
	set_state(PAUSED);
	printf("\nRobotics Cape Initialized\n");

	return 0;
}
int post_report(const string from_filename, const string device_mac, const map<int, Sensor*>& sa)
{
    	int esito=ERROR;
	string server_response_s;
	server_response_s.assign("null");
	
	Json::Reader reader;
	ifstream in_report_file;	//input file containing past reports (not yet dispatched to server)
	ofstream out_report_file;	//output file containing the remaining reports after this post (max 50 are sent)
	int num_extracted_lines=0;	//num of lines extracted from file: if it is 0 then no full report must be sent!
	string report_line; 		//line extracted from file (it will contain one unparsed report)
	Json::Value report;						//a single report extracted from file	
	Json::Value report_array = Json::Value(Json::arrayValue);	//saved reports array (parsed from file)


	//Open File 
	in_report_file.open(from_filename, ios::in );
	if(!in_report_file.is_open())
	{
		cout<<"||/ CRITICAL ERROR: Could not find source buffer file!!"<<endl;
		return esito;
	}
	else
	{
		//Open destination file for reports not being sent now (if there are too many or with problems)
		out_report_file.open("new_"+from_filename, ios::out);
		if(!out_report_file.is_open())
		{
			cout<<"||/ CRITICAL ERROR: Could not create destination buffer file!!"<<endl;
			return esito;
		}
	}

	//Parsing saved reports from input report file
	while( getline(in_report_file,report_line) )
	{
		/*
		//Parsing lines and creating elements of JsonArray Sensor_values:
		string fields[]={"value_timestamp","average_value","local_feed_id","variance","units_of_measurement"};
		string delimiter = "##";
		string token;	
		int i=0;
		size_t pos = 0;
		
		while ((pos = report_line.find(delimiter)) != std::string::npos) 
		{
			token = report_line.substr(0, pos);
			int pos1= token.find_first_of("=");
			report[fields[i]]=token.substr(pos1+1,token.size());
	     		i++;
	    		report_line.erase(0, pos + delimiter.length());
		}
		*/
		
		
		//Extract only a maximum number of measure lines per report sent!
		if( num_extracted_lines < 1000 )//IF current number of lines extracted is less than N
		{
			if( reader.parse(report_line,report) )	//PARSE current line from input_file and CHECK for error
			{
				report_array.append(report);		//NO ERROR: append the parsed line (json format) to report ready to be sent
			}
			else
			{
				out_report_file<<report_line<<"\n";	//ERROR: store the line AS IS to output_file (next report I will try again)
			}
		}
		else				//ELSE (we have already parsed at least N lines)
		{
			out_report_file<<report_line<<"\n";	//ALWAYS store the extracted line to output_file (next report I will fetch other N lines)
		}
		
		num_extracted_lines++;		//Increment number of lines computed

	}	
	in_report_file.close();
	out_report_file.close();
	
	
	if(num_extracted_lines > 0)	//check if input_file was not empty..
	{
		//Declaring COMPLETE Json
		Json::Value json_post;
	
		//Assembling the "position" part: geolocalization data
		Json::Value position;
			//Getting milliseconds since Epoch and converting it to string...
			stringstream textconverter;
			textconverter << std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch() ).count();
		position["kind"]="latitude#location";
		position["timestampMs"]= textconverter.str();
		position["latitude"]="45.067616";
		position["longitude"]="7.622660";
		position["accuracy"]="5000";
		position["height_meters"]="240";
	
		//Assembling COMPLETE Json
		json_post["position"]=position;
		json_post["sensor_values"]=report_array;	//attaching the array of reports fetched from file
		json_post["send_timestamp"]=getTimeStamp();
		json_post["raspb_wifi_mac"]=device_mac;

		//Just one HTTP POST call to the Server for all report selected
		esito=http_post_auth( params["report"].get("API_URL","").asString() + "device/" +device_mac+"/posts", json_post.toStyledString(), server_response_s);
		//cerr<<"\nRISPOSTA SERVER SU POST REPORT DI "<<getTimeStamp()<<":\n"<<server_response_s<<endl;
		//cout<<json_post<<endl;

		//.. and If http_post is ok --> delete the old file and rename the new as old
		if (esito==NICE)
		{
			remove(from_filename.c_str());
			rename( ("new_"+from_filename).c_str() , from_filename.c_str());

			/* OLD DELETE
			//Open New file as output
			ofstream ofs;
			ofs.open(from_filename, std::ofstream::out | std::ofstream::trunc);
			ofs.close();
			*/
		}
		else	//just delete the new file: the old file will be kept for next trial
		{
			remove( ("new_"+from_filename).c_str() );
		}
	}
	else
	{
		esito=ABORTED;	
	}
    

	return esito;

}
Exemple #10
0
int
main(int argc, char **argv)
{
	show_steps = 0;
	
	remove("input.txt");
	remove("output.txt");
	remove("tmpa.txt");
	remove("tmpb.txt");
	
	if (argc == 1 || argc > 3) {
		help();
		exit(1);
	} else {
	
		int option;		
		
		/* opcje */
		char optstring[] = ":skr:f:"; 
		while((option = getopt(argc,argv,optstring)) != -1) {
			switch(option) {
			 case 's' :
					show_steps = 1;
					break;
			 case 'k' :
					printf("Wprowadz rekordy i potwierdz je znakiem ENTER:\n");
					path_file = "input.txt";
					key_reads(path_file);
					run();
					break;
			 case 'r' :
					if(*optarg == 'f' || *optarg == 'k' || *optarg == 's') {
						printf("Bledny argument opcji -r \n\n");
						help();
						exit(1);
					}

					int records;
					records = atoi(optarg);					
					path_file = "input.txt";
					printf("Generowanie losowych rekordow.\n\n");
					rand_records(path_file, records);
					run();
					break;
			 case 'f' :
					if(*optarg == 'r' || *optarg == 'k' || *optarg == 's') {
						printf("Bledny argument opcji -f \n\n");
						help();
						exit(1);
					}

					path_file = optarg;
					run();
					break;
			 case ':' : /* brakuje argumentu w opcji */
					printf("Opcja -%c wymaga argumentu\n\n",optopt);
					help();
					exit(1);
			 case '?' :
			 default :
					help();
					exit(1);
			} 
		}
		
		if(argv[optind] == NULL || argv[optind + 1] == NULL) {
			help();
			exit(1);
		}
	}

	return 0;
}
/******************************************************************
*	int cleanup_cape()
*	shuts down library and hardware functions cleanly
*	you should call this before your main() function returns
*******************************************************************/
int cleanup_cape(){
	set_state(EXITING);
	
	// allow up to 3 seconds for thread cleanup
	struct timespec thread_timeout;
	clock_gettime(CLOCK_REALTIME, &thread_timeout);
	thread_timeout.tv_sec += 3;
	int thread_err = 0;
	thread_err = pthread_timedjoin_np(pause_pressed_thread, NULL, &thread_timeout);
	if(thread_err == ETIMEDOUT){
		printf("WARNING: pause_pressed_thread exit timeout\n");
	}
	thread_err = 0;
	thread_err = pthread_timedjoin_np(pause_unpressed_thread, NULL, &thread_timeout);
	if(thread_err == ETIMEDOUT){
		printf("WARNING: pause_unpressed_thread exit timeout\n");
	}
	thread_err = 0;
	thread_err = pthread_timedjoin_np(mode_pressed_thread, NULL, &thread_timeout);
	if(thread_err == ETIMEDOUT){
		printf("WARNING: mode_pressed_thread exit timeout\n");
	}
	thread_err = 0;
	thread_err = pthread_timedjoin_np(mode_unpressed_thread, NULL, &thread_timeout);
	if(thread_err == ETIMEDOUT){
		printf("WARNING: mode_unpressed_thread exit timeout\n");
	}
	thread_err = 0;
	thread_err = pthread_timedjoin_np(imu_interrupt_thread, NULL, &thread_timeout);
	if(thread_err == ETIMEDOUT){
		printf("WARNING: imu_interrupt_thread exit timeout\n");
	}
	
	#ifdef DEBUG
	printf("turning off GPIOs & PWM\n");
	#endif
	set_led(GREEN,LOW);
	set_led(RED,LOW);	
	disable_motors();
	deselect_spi1_slave(1);	
	deselect_spi1_slave(2);	
	disable_servo_power_rail();
	
	#ifdef DEBUG
	printf("turning off PRU\n");
	#endif
	prussdrv_pru_disable(0);
	prussdrv_pru_disable(1);
    prussdrv_exit();
	
	#ifdef DEBUG
	printf("deleting PID file\n");
	#endif
	FILE* fd;
	// clean up the pid_file if it still exists
	fd = fopen(PID_FILE, "r");
	if (fd != NULL) {
		// close and delete the old file
		fclose(fd);
		remove(PID_FILE);
	}
	
	printf("\nExiting Cleanly\n");
	return 0;
}
T MyQueue<T>::dequeue(){
    return remove(first());;
}
T MyStack<T>::pop(){
    return remove(last());
}
Exemple #14
0
static int os_remove (lua_State *L) {
  const char *filename = luaL_checkstring(L, 1);
  return os_pushresult(L, remove(filename) == 0, filename);
}
Exemple #15
0
int main(int argc, char *argv[])
{
   char buf[256] = "";
   FILE *f = NULL;
   int flip_slashes = 0;
   int ret, i, j;
   char *p;

   if (argc < 2) {
      printf("Usage: runner program args\n");
      return 1;
   }

   for (i=1; i<argc; i++) {
      if ((strcmp(argv[i], "\\") == 0) || (strcmp(argv[i], "\\\\") == 0)) {
	 flip_slashes = 1;
      }
      else if (strcmp(argv[i], "@") == 0) {
	 if (!f) {
	    f = fopen("_tmpfile.arg", "w");

	    if (!f) {
	       printf("Error writing _tmpfile.arg\n");
	       return 1;
	    }
	 }
      }
      else if (f) {
	 if (flip_slashes) {
	    for (j=0; argv[i][j]; j++) {
	       if (argv[i][j] == '/')
		  fputc('\\', f);
	       else
		  fputc(argv[i][j], f);
	    }
	    fputc('\n', f);
	 }
	 else
	    fprintf(f, "%s\n", argv[i]);
      }
      else {
	 if (buf[0])
	    strncat(buf, " ", sizeof(buf)-1);

	 if (flip_slashes) {
	    j = strlen(buf);
	    strncat(buf, argv[i], sizeof(buf)-1);
	    while (buf[j]) {
	       if (buf[j] == '/')
		  buf[j] = '\\';
	       j++;
	    }
	 }
	 else
	    strncat(buf, argv[i], sizeof(buf)-1);
      }
   }

   if (f) {
      fclose(f);
      strncat(buf, " @_tmpfile.arg", sizeof(buf)-1);
   }

   p = strchr(buf, ' ');
   if (p) {
      if (strlen(p) >= 126) {
	 fprintf(stderr, "Runner oops: command line is longer than 126 characters!\n");
	 remove("_tmpfile.arg");
	 return 1; 
      }
   }

   ret = system(buf);

   remove("_tmpfile.arg");

   return ret;
}
Exemple #16
0
void
sockunlink(void)
{
	if (socketname[0])
		remove(socketname);
}
Exemple #17
0
int get(int sockfd, char *remote_file, char *local_file) {
    int len,
        pkt_num = 1;
    char request[512];
    struct file_info fi;
    uint8_t successful = FALSE;

    /* Create local file */
    strcpy(fi.filename, local_file);
    strcpy(fi.mode, MODE_OCTET); //TODO
    fi.readonly = FALSE;

    if (file_init(&fi) == ERRNO_FOPEN) {
        error_num(6);
        return -1;
    }

    struct pkt_request req;
    req.opcode = PKT_RRQ;
    strcpy(req.filename, remote_file);
    strcpy(req.mode, MODE_OCTET); // TODO
    len = serialize_request(&req, request);

    dccp_send(sockfd, request, len);

    while (TRUE) {
        int bytes;
        char buf[BUF_SIZE];

        if ((bytes = recv(sockfd, buf, BUF_SIZE, 0)) <= 0) {
            /* Client shut down */
            if (bytes == 0) {
                //TODO client shut down
                error_num(4);
                break;
            } else  {
                //TODO error
            }
        }

        printf("PKT %d\n", pkt_num++);

        uint16_t opcode = ntohs(*(uint16_t *) buf);

        /* Handle incoming packet */
        if (opcode == PKT_DATA) {
            uint32_t block = ntohs(*(uint32_t *) (buf + B2));
            char *data = buf + B2 + B4;

            printf("block: %d\n", block);

            /* Ignore data with wrong block number */
            if (block == fi.cur_block + 1) {
                append_block(&fi, data, bytes - B2 - B4);
            } else if (block <= fi.cur_block) { // resend ack for lost packet
                send_ack(sockfd, block);
                continue;
            } else {
                continue;
            }

            printf("last_bytes: %d\n", fi.last_numbytes);

            /* Send ACK */
    if (pkt_num != 2 && pkt_num != 3 && pkt_num != 4) // DEBUG REMOVE
            send_ack(sockfd, block); 

            if (fi.last_numbytes < BLOCKSIZE) {
                // transfer finished
                successful = TRUE;
                break; // TODO not break, wait for timeout
            }

        } else if (opcode == PKT_ACK) {

        } else if (opcode == PKT_ERROR) {

        } else {

        }
    }

    file_close(&fi);
    if (!successful)
        remove(fi.filename);
    return 0;
}
Exemple #18
0
int initialize_cape(){
	FILE *fd; 			// opened and closed for each file
	char path[128]; // buffer to store file path string
	int i = 0; 			// general use counter
	
	printf("\n");

	// check if another project was using resources
	// kill that process cleanly with sigint if so
	fd = fopen(LOCKFILE, "r");
	if (fd != NULL) {
		int old_pid;
		fscanf(fd,"%d", &old_pid);
		if(old_pid != 0){
			printf("warning, shutting down existing robotics project\n");
			kill((pid_t)old_pid, SIGINT);
			sleep(1);
		}
		// close and delete the old file
		fclose(fd);
		remove(LOCKFILE);
	}
	
	
	// create new lock file with process id
	fd = fopen(LOCKFILE, "ab+");
	if (fd < 0) {
		printf("\n error opening LOCKFILE for writing\n");
		return -1;
	}
	pid_t current_pid = getpid();
	printf("Current Process ID: %d\n", (int)current_pid);
	fprintf(fd,"%d",(int)current_pid);
	fflush(fd);
	fclose(fd);
	
	// ensure gpios are exported
	printf("Initializing GPIO\n");
	for(i=0; i<NUM_OUT_PINS; i++){
		if(gpio_export(out_gpio_pins[i])){
			printf("failed to export gpio %d", out_gpio_pins[i]);
			return -1;
		};
		gpio_set_dir(out_gpio_pins[i], OUTPUT_PIN);
	}
	
	// set up default values for some gpio
	disable_motors();
	deselect_spi1_slave(1);	
	deselect_spi1_slave(2);	
	

	//Set up PWM
	printf("Initializing PWM\n");
	i=0;
	for(i=0; i<4; i++){
		strcpy(path, pwm_files[i]);
		strcat(path, "polarity");
		fd = fopen(path, "a");
		if(fd<0){
			printf("PWM polarity not available in /sys/class/devices/ocp.3\n");
			return -1;
		}
		//set correct polarity such that 'duty' is time spent HIGH
		fprintf(fd,"%c",'0');
		fflush(fd);
		fclose(fd);
	}
	
	//leave duty cycle file open for future writes
	for(i=0; i<4; i++){
		strcpy(path, pwm_files[i]);
		strcat(path, "duty");
		pwm_duty_pointers[i] = fopen(path, "a");
	}
	
	//read in the pwm period defined in device tree overlay .dts
	strcpy(path, pwm_files[0]);
	strcat(path, "period");
	fd = fopen(path, "r");
	if(fd<0){
		printf("PWM period not available in /sys/class/devices/ocp.3\n");
		return -1;
	}
	fscanf(fd,"%i", &pwm_period_ns);
	fclose(fd);
	
	// mmap pwm modules to get fast access to eQep encoder position
	// see mmap_eqep example program for more mmap and encoder info
	printf("Initializing eQep Encoders\n");
	int dev_mem;
	if ((dev_mem = open("/dev/mem", O_RDWR | O_SYNC))==-1){
	  printf("Could not open /dev/mem \n");
	  return -1;
	}
	pwm_map_base[0] = mmap(0,getpagesize(),PROT_READ|PROT_WRITE,MAP_SHARED,dev_mem,PWM0_BASE);
	pwm_map_base[1] = mmap(0,getpagesize(),PROT_READ|PROT_WRITE,MAP_SHARED,dev_mem,PWM1_BASE);
	pwm_map_base[2] = mmap(0,getpagesize(),PROT_READ|PROT_WRITE,MAP_SHARED,dev_mem,PWM2_BASE);
	if(pwm_map_base[0] == (void *) -1) {
		printf("Unable to mmap pwm \n");
		return(-1);
	}
	close(dev_mem);
	
	// Test eqep and reset position
	for(i=1;i<3;i++){
		if(set_encoder_pos(i,0)){
			printf("failed to access eQep register\n");
			printf("eQep driver not loaded\n");
			return -1;
		}
	}
	
	//set up function pointers for button press events
	printf("starting button interrupts\n");
	set_pause_pressed_func(&null_func);
	set_pause_unpressed_func(&null_func);
	set_mode_pressed_func(&null_func);
	set_mode_unpressed_func(&null_func);
	initialize_button_handlers();
	
	// Load binary into PRU
	printf("Starting PRU servo controller\n");
	if(initialize_pru_servos()){
		printf("WARNING: PRU init FAILED");
	}
	
	// Print current battery voltage
	printf("Battery Voltage = %fV\n", getBattVoltage());
	
	// Start Signal Handler
	printf("Enabling exit signal handler\n");
	signal(SIGINT, ctrl_c);	
	
	// all done
	set_state(PAUSED);
	printf("\nRobotics Cape Initialized\n");

	return 0;
}
//--------------------------------------------------------------
ofxBulletSoftBody::~ofxBulletSoftBody() {
    remove();
}
int main(int argc, char* argv[])
{

  // enough arguments ?

  if (argc < 2) {
    fprintf(stderr, "Usage: %s [OPTIONS] state\n"
	    "\n   -g            debug"
	    "\n   -q            quiet"
	    "\n   -s            write (radial) densities into file"
	    "\n   -l LABEL	use label"
	    "\n   -r RANGE      radial range"
	    "\n   -c RANGE      coordinate range\n",
	    argv[0]);
    exit(-1);
  }

  int debug=0, quiet=0;
  int save=0;
  int shape=1;
  int view=1;

  double xmax=5.5;
  double rmax=5.4;

  int npoints=40+1;
  int izcw=5;

  char* label = NULL;

  char c;
  while ((c = getopt(argc, argv, "c:r:l:gqsn")) != -1)
    switch (c) {
    case 'g':
      debug=1;
      break;
    case 'q':
      quiet=1;
      break;
    case 's':
      save=1;
      break;
    case 'n':
      shape=0;
      break;
    case 'l':
      label=optarg;
      break;
    case 'c':
      xmax = atof(optarg);
      break;
    case 'r':
      rmax = atof(optarg);
      break;
    }	


  char* slaterdetfile = argv[optind];

  SlaterDet Q;
  readSlaterDetfromFile(&Q, slaterdetfile);

  if (!label)
    label = nucleusIDLformat(nucleusname(Q.A, Q.Z));
  
  double* dens = (double*) malloc(3*SQR(npoints)*sizeof(double));
  double* rdens = (double*) malloc(3*npoints*sizeof(double));

  // write densities to data files

  char datafile[255];
  FILE *datafp;
  int v;

  snprintf(datafile, 255, "%s.rdens", slaterdetfile);;
  if (!(datafp = fopen(datafile, "w"))) {
    fprintf(stderr, "couldn't open %s for writing\n", datafile);
    exit(-1);
  }

  int i,j;
  // coordinate space densities
  if (shape) {
    calcDensitiesCoordinate(&Q, view, npoints, xmax, dens);

    int axis=2;
    for (j=0; j<npoints; j++) {
      for (i=0; i<npoints; i++)
	fprintf(datafp, "%f  ", dens[j*npoints+i]/rho0);
      fprintf(datafp, "\n");
    }
  }

  // radial densities
  calcRadialDensitiesCoordinate(&Q, izcw, npoints, rmax, rdens);
  
  for (i=0; i<npoints; i++)
    fprintf(datafp, "%15.8g    ", rdens[i]);
  fprintf(datafp, "\n");
  for (i=0; i<npoints; i++)
    fprintf(datafp, "%15.8g    ", rdens[i+  npoints]);
  fprintf(datafp, "\n");
  for (i=0; i<npoints; i++)
    fprintf(datafp, "%15.8g    ", rdens[i+2*npoints]);
  fprintf(datafp, "\n");

  fclose(datafp);

  // write radial densities into file
  if (save) {
    char rdensfile[255];
    FILE* rdensfp;

    snprintf(rdensfile, 255, "%s.dens.dat", slaterdetfile);
    if (!(rdensfp = fopen(rdensfile, "w"))) {
      fprintf(stderr, "couldn't open %s for writing\n", rdensfile);
      exit(-1);
    }  
    
    for (i=0; i<npoints; i++)
      fprintf(rdensfp, "%8.3f\t%15.8g\t%15.8g\t%15.8g\n",
	      rmax/(npoints-1)*i,
	      rdens[i],
	      rdens[i+  npoints],
	      rdens[i+2*npoints]);
    
    fclose(rdensfp);
  }
    

  // writing IDL script

  char scriptfile[255];
  FILE* scriptfp;

  char* fmdhome;

  if (!(fmdhome = getenv("FMD"))) {
    fprintf(stderr, "environment variable FMD not defined\n");
    exit(-1);
  }

  snprintf(scriptfile, 255, "%s.rdens.script", slaterdetfile);
  if (!(scriptfp = fopen(scriptfile, "w"))) {
    fprintf(stderr, "couldn't open %s for writing\n", scriptfile);
    exit(-1);
  }

  fprintf(scriptfp, 
	  "; plot densities of nuclei\n; written by calcdens\n\n");
  fprintf(scriptfp, "densxy=fltarr(%d,%d,%d)\n", 
	  npoints, npoints, 1);\
  fprintf(scriptfp, "rdens=fltarr(%d,3,%d)\n",
	  npoints, 1);

  fprintf(scriptfp, "!path = '%s/lib:' + !path\n", fmdhome);
  fprintf(scriptfp, "openr, unit, '%s', /get_lun\n", datafile);
  if (shape)
    fprintf(scriptfp, "readf, unit, densxy\n");
  fprintf(scriptfp, "readf, unit, rdens\n");
  fprintf(scriptfp, "free_lun, unit\n");
  
  fprintf(scriptfp, "\n.run multipost, densityplot, radialdensityplot\n");
  fprintf(scriptfp, "!p.thick = 1.5\n");
  fprintf(scriptfp, "pos = initpost('%s.rdens.eps', %d, 1, gapx=2.0, /color)\n",
	  slaterdetfile, 1+shape);
  fprintf(scriptfp, "!x.minor = 0\n!y.minor = 0\n");
  fprintf(scriptfp, "loadct, 3\n");

  fprintf(scriptfp, "!p.position = pos(0,*)\n");
  if (shape) {
    fprintf(scriptfp, "densityplot, densxy(*,*,%d), %d, %f, %f, %f, %f, $\n",
	    0, view, -xmax, xmax, -xmax, xmax);
    fprintf(scriptfp, "\t/cut, /coordinate, /cont, /dens, key = '%s'\n", 
	    label);

    fprintf(scriptfp, "!p.position = pos(1,*)\n");
  }
  fprintf(scriptfp, "!x.minor = 4\n!y.minor = 0\n");
  fprintf(scriptfp, "radialdensityplot, rdens(*,*,0), %f, $\n", rmax);
  fprintf(scriptfp, "\t/coordinate, key = \"%s\", /legend, /col\n",
	  label);
  fprintf(scriptfp, "exit\n");

  fclose(scriptfp);

  // calling IDL

  char call[255];

  snprintf(call, 255, "idl < %s", scriptfile);
  system(call);

  char epsfile[255];
  snprintf(epsfile, 255, "%s.rdens.eps", slaterdetfile);
  // calling gv

  if (!quiet) {
    snprintf(call, 255, "gv %s &", epsfile);
    system(call);
  }

  // clean up

  if (!debug) {
    remove(datafile); 
    remove(scriptfile);
  }

  return 0;
}
Exemple #21
0
int main() 
{
    static const unsigned int testFileSize = 1 * 1024 * 1024;
    static SDFileSystem       sdFatFileSystem(p5, p6, p7, p8, "sd");
    static Timer              timer;
    FILE*                     pFile = NULL;
    size_t                    bytesTransferred = 0;
    size_t                    i = 0;
    int                       seekResult = -1;
    char                      filenameBuffer[256];
    static __attribute((section("AHBSRAM0"),aligned)) unsigned char buffer[16 * 1024];
    static __attribute((section("AHBSRAM1"),aligned)) char          cache[16 * 1024];
    

    // Search for a unique filename to test with.
    for (i = 0 ; ; i++)
    {
        snprintf(filenameBuffer, sizeof(filenameBuffer), "/sd/tst%u.bin", i);
        printf("Trying %s...", filenameBuffer);
        pFile = fopen(filenameBuffer, "r");
        if (!pFile)
        {
            printf("free!\n");
            break;
        }
        printf("exists!\n");
        fclose(pFile);
    }
    
    printf("Performing write test...\n");
    memset(buffer, 0x55, sizeof(buffer));
    
    // Write out large file to SD card and time the write.
    pFile = fopen(filenameBuffer, "w");
    if (!pFile)
    {
        printf("error: Failed to create %s", filenameBuffer);
        perror(NULL);
        exit(-1);
    }
    setvbuf(pFile, cache, _IOFBF, sizeof(cache));

    timer.start();
    for (i = 0 ; i < testFileSize / sizeof(buffer) ; i++)
    {
        bytesTransferred = fwrite(buffer, 1, sizeof(buffer), pFile);
        if (bytesTransferred != sizeof(buffer))
        {
            printf("error: Failed to write to %s", filenameBuffer);
            perror(NULL);
            exit(-1);
        }
    }
    unsigned int totalTicks = (unsigned int)timer.read_ms();
    unsigned int totalBytes = ftell(pFile);
    fclose(pFile);

    printf("Wrote %u bytes in %u milliseconds.\n", totalBytes, totalTicks);
    printf("%f bytes/second.\n", totalBytes / (totalTicks / 1000.0f));
    printf("%f MB/second.\n", (totalBytes / (totalTicks / 1000.0f)) / (1024.0f * 1024.0f));


    printf("Performing read test...\n");
    pFile = fopen(filenameBuffer, "r");
    if (!pFile)
    {
        printf("error: Failed to open %s", filenameBuffer);
        perror(NULL);
        exit(-1);
    }
    setvbuf(pFile, cache, _IOFBF, sizeof(cache));
    
    timer.reset();
    for (;;)
    {
        bytesTransferred = fread(buffer, 1, sizeof(buffer), pFile);
        if (bytesTransferred != sizeof(buffer))
        {
            if (ferror(pFile))
            {
                printf("error: Failed to read from %s", filenameBuffer);
                perror(NULL);
                exit(-1);
            }
            else
            {
                break;
            }
        }
    }
    totalTicks = (unsigned int)timer.read_ms();
    totalBytes = ftell(pFile);

    printf("Read %u bytes in %u milliseconds.\n", totalBytes, totalTicks);
    printf("%f bytes/second.\n", totalBytes / (totalTicks / 1000.0f));
    printf("%f MB/second.\n", (totalBytes / (totalTicks / 1000.0f)) / (1024.0f * 1024.0f));
    
    
    printf("Validating data read.  Not for performance measurement.\n");
    seekResult = fseek(pFile, 0, SEEK_SET);
    if (seekResult)
    {
        perror("error: Failed to seek to beginning of file");
        exit(-1);
    }
    
    for (;;)
    {
        unsigned int   j;
        unsigned char* pCurr;
        
        memset(buffer, 0xaa, sizeof(buffer));
        bytesTransferred = fread(buffer, 1, sizeof(buffer), pFile);
        if (bytesTransferred != sizeof(buffer) && ferror(pFile))
        {
            printf("error: Failed to read from %s", filenameBuffer);
            perror(NULL);
            exit(-1);
        }
        
        for (j = 0, pCurr = buffer ; j < bytesTransferred ; j++)
        {
            if (*pCurr++ != 0x55)
            {
                printf("error: Unexpected read byte encountered.");
                exit(-1);
            }
        }
        
        if (bytesTransferred != sizeof(buffer))
            break;
    }
    totalBytes = ftell(pFile);
    printf("Validated %u bytes.\n", totalBytes);
    fclose(pFile);

    printf("Determine size of file through fseek and ftell calls.\n");
    pFile = fopen(filenameBuffer, "r");
    seekResult = fseek(pFile, 0, SEEK_END);
    long size = ftell(pFile);
    if ((long)testFileSize != size)
    {
        printf("error: ftell returned %ld instead of the expected value of %u.\n", size, testFileSize);
        exit(-1);
    }
    fclose(pFile);
    
    printf("Create directories.\n");
    remove("/sd/testdir1/z");
    remove("/sd/testdir1/a");
    remove("/sd/testdir1");
    int mkdirResult = mkdir("/sd/testdir1", 0);
    if (mkdirResult)
    {
        perror("error: mkdir(/sd/testdir1) failed");
        exit(-1);
    }
    mkdirResult = mkdir("/sd/testdir1/a", 0);
    if (mkdirResult)
    {
        perror("error: mkdir(/sd/testdir1/a) failed");
        exit(-1);
    }
    mkdirResult = mkdir("/sd/testdir1/z", 0);
    if (mkdirResult)
    {
        perror("error: mkdir(/sd/testdir1/z) failed");
        exit(-1);
    }

    // Enumerate all content on mounted file systems.
    printf("\nList all files in /sd...\n");
    _RecursiveDir("/sd");

    printf("Cleanup test directories.\n");
    int removeResult = remove("/sd/testdir1/z");
    if (removeResult)
    {
        perror("error: remove(sd/testdir1/z) failed");
        exit(-1);
    }
    removeResult = remove("/sd/testdir1/a");
    if (removeResult)
    {
        perror("error: remove(sd/testdir1/a) failed");
        exit(-1);
    }
    removeResult = remove("/sd/testdir1");
    if (removeResult)
    {
        perror("error: remove(sd/testdir1) failed");
        exit(-1);
    }
    
    printf("Remove test file.\n");
    removeResult = remove(filenameBuffer);
    if (removeResult)
    {
        perror("error: remove() failed");
        exit(-1);
    }

    return 0;
}
Exemple #22
0
int
smart_rename (const char *from, const char *to, int preserve_dates)
{
  bfd_boolean exists;
  struct stat s;
  int ret = 0;

  exists = lstat (to, &s) == 0;

#if defined (_WIN32) && !defined (__CYGWIN32__)
  /* Win32, unlike unix, will not erase `to' in `rename(from, to)' but
     fail instead.  Also, chown is not present.  */

  if (exists)
    remove (to);

  ret = rename (from, to);
  if (ret != 0)
    {
      /* We have to clean up here.  */
      non_fatal (_("unable to rename '%s' reason: %s"), to, strerror (errno));
      unlink (from);
    }
#else
  /* Use rename only if TO is not a symbolic link and has
     only one hard link, and we have permission to write to it.  */
  if (! exists
      || (!S_ISLNK (s.st_mode)
	  && S_ISREG (s.st_mode)
	  && (s.st_mode & S_IWUSR)
	  && s.st_nlink == 1)
      )
    {
      ret = rename (from, to);
      if (ret == 0)
	{
	  if (exists)
	    {
	      /* Try to preserve the permission bits of TO. Don't
	       * restore special bits. */
	      chmod (to, s.st_mode & 0777);
	    }
	}
      else
	{
	  /* We have to clean up here.  */
	  non_fatal (_("unable to rename '%s' reason: %s"), to, strerror (errno));
	  unlink (from);
	}
    }
  else
    {
      ret = simple_copy (from, to);
      if (ret != 0)
	non_fatal (_("unable to copy file '%s' reason: %s"), to, strerror (errno));

      if (preserve_dates)
	set_times (to, &s);
      unlink (from);
    }
#endif /* _WIN32 && !__CYGWIN32__ */

  return ret;
}
Exemple #23
0
void dccpktq_clear(DCCPktQ *q) {
  DCCPktElem *e;
  cli();
  while((e = q->read) != NULL) remove(q, e);
  sei();
}
Exemple #24
0
int main(int argc, char *argv[])
{
	char tempFile[strlen(argv[1]) + 1];
	strcpy(tempFile, argv[1]);
	strcat(tempFile, "tempIndex.txt");
	char* path = argv[0];
	path[strlen(argv[0]) - 3] = '\0';

	if (signal(SIGCHLD, SIG_IGN) == SIG_ERR)
		perror("Error in function signal");

	// number of files to concatenate and sort
	int n = strtol(argv[2], NULL, 10);

	// create and get file descriptor for tempFile
	int fd = open(tempFile, O_WRONLY | O_CREAT, 0750); 
	if (fd == -1)
		perror("Error creating tempIndex");

	int cenas = dup(STDOUT_FILENO);
	if (dup2(fd, STDOUT_FILENO) == -1)
		perror("Error duplicating descriptor");

	// concatenate files
	int i, status;
	for (i = 1; i <= n; i++)
	{
		pid_t pid = fork();
		if (pid == 0) // child
		{
			char fileName[20];
			strcpy(fileName, "index");
			char buffer[5];
			sprintf(buffer, "%d", i);
			strcat(fileName, buffer);
			char file[strlen(path) + 1];
			strcpy(file, path);
			strcat(fileName, ".txt");
			strcat(file, fileName);
			execlp("cat", "cat", file, NULL);
		}
		else if (fork > 0) // parent
			wait(&status);
		else
			perror("Error creating fork");
	}

	// sort files
	pid_t pid = fork();
	if (pid == 0)
		// flag V to interpret numbers as integers and not as characters	
		// flag f to not distinguish lower case characters from upper case characters
		// flag o to write the result into temp File instead of the standard output
		execlp("sort", "sort", "-V", "-f", "-o", tempFile, tempFile, NULL);
	else if (fork < 0)
		perror("Error creating fork");

	wait(&status);

	dup2(cenas, STDOUT_FILENO);
	// create index
	char indexFile[strlen(argv[1]) + 1];
	strcpy(indexFile, argv[1]);
	strcat(indexFile, "index.txt");

	FILE* index = fopen(indexFile, "wa");
	FILE* tempIndex = fopen(tempFile, "r");
	char currentWord[20], location[10];
	char previousWord[20] = "";
	fputs("INDEX", index);
	
	while(fscanf(tempIndex, "%[^:]: %s\n", currentWord, location) == 2)
	{
		if (strcmp(previousWord, currentWord) == 0)
			fprintf(index, ", %s", location);
		else
		{
			strcpy(previousWord, currentWord);
			fprintf(index, "\n\n%s: %s", currentWord, location);
		}
	}

	if (remove(tempFile) != 0)
		perror("Error deleting file");

	return 0;
}
Exemple #25
0
bool test_dirscan(){
  int buffer_test[10000];
  for(size_t i = 0; i <array_count(buffer_test); i++){
    buffer_test[i] = i;
  }
  allocator * _allocator = trace_allocator_make();
  allocator * old_allocator = iron_get_allocator();
  iron_set_allocator(_allocator);
  
  dirscan ds = {0};
  //size_t max_diff_cnt = 0;
  //size_t max_file_cnt = 0;
  mkdir("dir test 1", 0777);
  mkdir("dir test 1/sub dir", 0777);
  memset(buffer_test, 10, sizeof(buffer_test));
  udpc_dirscan_update("dir test 1", &ds, false);
  ASSERT(ds.cnt == 0);
  write_buffer_to_file(buffer_test, sizeof(buffer_test), "dir test 1/test1" );
  buffer_test[0] += 10;
  write_buffer_to_file(buffer_test, sizeof(buffer_test), "dir test 1/test2" );
  iron_usleep(30000);  
  size_t s = 0;
  void * buffer = dirscan_to_buffer(ds, &s);
  dirscan copy = dirscan_from_buffer(buffer);
  dealloc(buffer);
  udpc_dirscan_update("dir test 1", &ds, false);

  dirscan_diff diff = udpc_dirscan_diff(copy, ds);
  ASSERT(diff.cnt == 2);
  ASSERT(diff.states[0] == DIRSCAN_NEW);
  udpc_dirscan_clear_diff(&diff);
  ASSERT(ds.type[0] == UDPC_DIRSCAN_FILE);
  remove("dir test 1/test1");
  iron_usleep(20000);
  udpc_dirscan_update("dir test 1", &ds, false);
  
  int idx = -1;
  if(strcmp(ds.files[0], "test1") == 0)
    idx = 0;
  else if(strcmp(ds.files[1], "test1") == 0)
    idx = 1;

  ASSERT(idx != -1);
  iron_usleep(30000);
  ASSERT(ds.cnt == 2);
  ASSERT(ds.type[idx] == UDPC_DIRSCAN_DELETED);

  buffer_test[0] += 10;
  write_buffer_to_file(buffer_test, sizeof(buffer_test), "dir test 1/test1" );
  udpc_dirscan_update("dir test 1", &copy, false);
  diff = udpc_dirscan_diff(ds, copy);
  ASSERT(diff.cnt == 1);
  ASSERT(diff.states[0] == DIRSCAN_NEW);
  udpc_dirscan_clear_diff(&diff);
  
  dirscan_clean(&copy);

  write_buffer_to_file(buffer_test, sizeof(buffer_test), "dir test 1/sub dir/test3" );
  udpc_dirscan_update("dir test 1", &ds, false);
  ASSERT(ds.cnt == 3);
  ASSERT(udpc_md5_compare(ds.md5s[idx], ds.md5s[2]));

  for(int i = 0; i < 10; i++){
    char filename[40];
    sprintf(filename, "dir test 1/sub dir/testx_%i", i);
    write_buffer_to_file(buffer_test, sizeof(buffer_test), filename );
  }
  udpc_dirscan_update("dir test 1", &ds, false);
  ASSERT(ds.cnt == 13);
 
  dirscan_clean(&ds);

  for(int i = 0; i < 10; i++){
    char filename[40];
    sprintf(filename, "dir test 1/sub dir/testx_%i", i);
    remove(filename);
  }
  
  ASSERT(!remove("dir test 1/test2"));
  ASSERT(!remove("dir test 1/sub dir/test3"));
  ASSERT(!remove("dir test 1/sub dir"));
  ASSERT(!remove("dir test 1/test1"));
  ASSERT(!remove("dir test 1"));
  iron_set_allocator(old_allocator);
  int used_pointers = (int) trace_allocator_allocated_pointers(_allocator);
  trace_allocator_release(_allocator);
  
  ASSERT(used_pointers == 0);
  return TEST_SUCCESS;
}
 inline bool erase(const TKey key) { return remove(key); }
	bool CFileSystem::removeDirectory(const char* szDirectoryPath)
	{
		return remove(szDirectoryPath) == 0;
	}
Exemple #28
0
static int io_remove (lua_State *L) {
  return pushresult(L, remove(luaL_check_string(L, 1)) == 0);
}
Exemple #29
0
void CodeDocument::replaceAllContent (const String& newContent)
{
    remove (0, getNumCharacters(), true);
    insert (newContent, 0, true);
}
Exemple #30
0
void ERR_RemoveErrorFile(void)
{
	remove(ErrorFileName());
}