Exemplo n.º 1
0
int file_getValidLine(FILE *fp, char **buffer_r)
{
	// get a valid line (not a blank-line)
	// 	from a file

	// exit code
	int excode;
	// stream buffer
	char *buffer;
	// finished flag
	int done;
	do
	{
		// read until EOF is reached,
		// 	or a non-blank line is found
		excode = file_getline(fp, buffer_r);
		buffer = *buffer_r;
		if (excode == 1)
			done = 1;
		else if (buffer[0] == '\0')
		{
			// empty line
			// re-run
			done = 0;
			free(buffer);
		}
		else
		{
			// finished
			done = 1;
		}
	} while (done == 0);
	return excode;
}
Exemplo n.º 2
0
/* convert locale alias to canonical name using LOCALE_ALIAS_FILE (presumably
   /usr/share/locale/locale.alias) and return it

   Returned string should be freed by caller.

   FIXME: this function can get easily confused by lines longer than BUFSIZE
   (but the worst thing that can happen is we return wrong locale name)
   the locale.alias format is nowhere described, so we assume every line
   consists of alias (row 1), some whitespace and canonical name */
static char*
locale_alias_convert(const char *locname)
{
#ifdef HAVE_LOCALE_ALIAS
  File *fla; /* locale.alias file */
  Buffer *buf;
  char *s,*p,*q;
  size_t n;
#endif /* HAVE_LOCALE_ALIAS */

  if (!locname)
    return NULL;

  /* Catch the special language name `none' */
  if (strcmp(locname, "none") == 0)
    return enca_strdup("__");

#ifdef HAVE_LOCALE_ALIAS
  /* try to read locale.alias */
  buf = buffer_new(0);
  fla = file_new(LOCALE_ALIAS_PATH, buf);
  if (file_open(fla, "r") != 0) {
    if (options.verbosity_level) {
      fprintf(stderr, "Cannot find locale.alias file.\n"
                      "This build of enca probably has been configured for "
                      "quite a different system\n");
    }
    file_free(fla);
    buffer_free(buf);
    return enca_strdup(locname);
  }

  /* scan locale.alias
     somewhat crude now */
  n = strlen(locname);
  p = NULL;
  s = (char*)buf->data; /* alias */
  while (file_getline(fla) != NULL) {
    if (strncmp(s, locname, n) == 0 &&
        (isspace(s[n]) || (s[n] == ':' && isspace(s[n+1])))) {
      p = s + n;
      /* skip any amount of whitespace */
      while (isspace(*p)) p++;
      q = p;
      /* anything up to next whitespace is the canonical locale name */
      while (*q != '\0' && !isspace(*q)) q++;
      *q = '\0';
      p = enca_strdup(p);
      break;
    }
  }
  file_close(fla);
  file_free(fla);

  buffer_free(buf);
  return p != NULL ? p : static_iso639_alias_convert(locname);
#else /* HAVE_LOCALE_ALIAS */
  return static_iso639_alias_convert(locname);
#endif /* HAVE_LOCALE_ALIAS */
}
Exemplo n.º 3
0
int main(int argc,  const char **argv)
{
    ArgState *state = arg_command_line(args,argv);
    if (! interactive) {
        if (array_len(incdirs) > 0) {
            printf("the include paths\n");
            FOR_ARR (str_t,P,incdirs)
                printf("'%s'\n",*P);
        }
        if (array_len(string_args) > 0) {
            printf("the string args\n");
            FOR_ARR (str_t,P,string_args)
                printf("'%s'\n",*P);
        }
        printf("flag a is %d\n",a);
    } else {
        char *line;
            printf("> ");
        while ((line = file_getline(stdin)) != NULL) {
            char **parts = str_split(line," ");
            // args_process assumes args start at second element, hence -1 here
            PValue v = arg_process(state,(const char**)parts-1);
            if (v != NULL) {
                printf("%s\n",value_tostring(v));
                unref(v);
            }
            dispose(parts,line);
            printf("> ");
            arg_reset_used(state);
        }        
    }
    return 0;
}
Exemplo n.º 4
0
int main(int argc, char **argv) {
    char *arg;

    char *address = NULL;
    char *language = NULL;

    bool use_json = false;

    string_array *languages = NULL;

    for (int i = 1; i < argc; i++) {
        arg = argv[i];
        if (string_equals(arg, "-h") || string_equals(arg, "--help")) {
            printf(LIBPOSTAL_USAGE);
            exit(EXIT_SUCCESS);
        } else if (string_equals(arg, "--json")) {
            use_json = true;
        } else if (address == NULL) {
            address = arg;
        } else if (!string_starts_with(arg, "-")) {
            if (languages == NULL) {
                languages = string_array_new();
            }
            string_array_push(languages, arg);
        }
    }

    if (address == NULL && (!use_json || isatty(fileno(stdin)))) {
        log_error(LIBPOSTAL_USAGE);
        exit(EXIT_FAILURE);
    }

    if (!libpostal_setup() || (languages == NULL && !libpostal_setup_language_classifier())) {
        exit(EXIT_FAILURE);
    }

    normalize_options_t options = get_libpostal_default_options();

    if (languages != NULL) {
        options.languages = languages->a;
        options.num_languages = languages->n;
    }

    if (address == NULL) {
        char *line;
        while ((line = file_getline(stdin)) != NULL) {
            print_output(line, options, use_json);
            free(line);
        }
    } else {
        print_output(address, options, use_json);
    }

    if (languages != NULL) {
        string_array_destroy(languages);
    }

    libpostal_teardown();
    libpostal_teardown_language_classifier();
}
Exemplo n.º 5
0
void parse_file(char* filename, char* target, bool execute) {
    // printf("target = %s\n\n", target);
    char* line = malloc(160*sizeof(char));
    char* token = malloc(160*sizeof(char));
    FILE* fp = file_open(filename);
    FILE* fpipe;
    bool firstTarg = strcmp(target, "all") == 0;
    bool closePipe = false;

    while((line = file_getline(line, fp)) != NULL) {
        token = strtok(line, ": \n");

        if(token != NULL && target != NULL) {
            if(strcmp(target, token) == 0) {            
     
                while((token = strtok(NULL, " \n")) != NULL) {
                    parse_file(filename, token, execute);
                    token = strtok(NULL, " \n");
                }
                
                while((line = file_getline(line,fp)) != NULL && strcmp(line, "end\n") != 0) {
                        if(execute) {
                            if((fpipe = (FILE*)popen(line, "w")) == NULL) {
                                printf("Pipe Error - Exit code 2\n");
                                exit(2);
                            }
                            if(firstTarg) {
                                closePipe = true;
                            }
                        } else {
                            printf("%s", line);
                        }
                }
            }
            
    // this loop will go through the given file, one line at a time
    // this is where you need to do the work of interpreting
    // each line of the file to be able to deal with it later
        }
    }
    if(fpipe != NULL && closePipe) {
        pclose(fpipe);
    }
    fclose(fp);
    free(token);
    free(line);
}
Exemplo n.º 6
0
/****************************** 
 * this is the function that, when given a proper filename, will
 * parse the dimefile and read in the rules
 ***************/
void parse_file(char* filename) {
	char* line = malloc(160*sizeof(char));
	FILE* fp = file_open(filename);
	while((line = file_getline(line, fp)) != NULL) {
	
	// this loop will go through the given file, one line at a time
	// this is where you need to do the work of interpreting
	// each line of the file to be able to deal with it later

	}
	fclose(fp);
	free(line);
}
Exemplo n.º 7
0
float * getDataB(char * filename, int n)
{
	float *a = (float *) malloc(sizeof(float) * n);
	char* line = malloc(300*sizeof(char));
	FILE * file = file_open(filename);
	int count = 0;

	while((line = file_getline(line,file)) != NULL)
	{
		a[count] = atof(line);
		count++;
	}
	fclose(file);
	free(line);
	return a;
}
Exemplo n.º 8
0
/****************************** 
 * this is the function that, when given a proper filename, will
 * parse the dimefile and read in the rules
 ***************/
rule_node_t* parse_file(char* filename) {
	char* buffer = malloc(160*sizeof(char));
	char* line;
	FILE* fp = file_open(filename);
	rule_node_t* rlist = NULL;
	rule_t* current_rule = NULL;
	while((line = file_getline(buffer, fp)) != NULL) {
		if(line[0] == '#') {
			// do nothing because this line is a comment
		} else {
			// not a comment
			if(current_rule != NULL) {
				if(line[0] == '}') {
					// then this is the closing } of a rule
					rule_node_t* node = rule_node_create(current_rule);
					node->next = rlist;
					rlist = node;
					current_rule = NULL;
				} else {
					// this is just another command line in the rule
					char* trim_line = trim(line);
					rule_add_commandline(current_rule, trim_line);
					free(trim_line);
				}
			} else {
				if(strchr(line, ':') != NULL) {
					// this is the start of a rule
					char* trim_targ = trim(strtok(line, ":"));
					current_rule = rule_create(trim_targ);
					free(trim_targ);
					char* alldeps = strtok(NULL, ":");
					char* dep = strtok(alldeps, " ");
					if(dep != NULL) {
						do {
							if(*dep != '{') {
								rule_add_dep(current_rule, dep);
							}
						} while((dep = strtok(NULL, " ")) != NULL);
					}
				}
			}
		}
	}
	fclose(fp);
	free(buffer);
	return rlist;
}
Exemplo n.º 9
0
queue* get_clients(char* file_path){
    FILE* fp = file_open(file_path);
    char* line = malloc(512 * sizeof(char));
    queue* clients = malloc(sizeof(queue));
 	int count = 0;
    //For each line in the client file, add a path string to the queue
    while((line = file_getline(line, fp)) != NULL){
        char* client = malloc(sizeof(char) * strlen(line) + 1);
        strcpy(client, line);
        trim(client);
        insert(clients, client);
        count++;
    }
    free(line);

    return clients;
}
Exemplo n.º 10
0
Arquivo: main.c Projeto: parkx676/C
//This function will parse makefile input from user or default makeFile. 
int parse(char * lpszFileName)
{

	int nLine=0;
	char szLine[1024];
	char * lpszLine;
	FILE * fp = file_open(lpszFileName);
	char* deps[10];

	if(fp == NULL)
	{
		return -1;
	}

	while(file_getline(szLine, fp) != NULL) 
	{
		if(szLine[0] == '\n') { continue; }
		nLine++;
		// this loop will go through the given file, one line at a time
		// this is where you need to do the work of interpreting
		// each line of the file to be able to deal with it later

		// Remove newline character at end if there is one
		lpszLine = strtok(szLine, "\n");

		
		int i;
		if(lpszLine[0] == '\t'){

			// skip if all whitespace
			if(lpszLine[1] == '\t' || lpszLine[1] == '\n' || lpszLine[1] == ' '){
				continue;
			}

			// write the command associated with a target to the command char[] variable.
			char* command;
			command = (char *) calloc(64, 1);
			for(i = 1; lpszLine[i] != '\0'; i++) {
				if(lpszLine[i] == '#'){
					break;
				}
				command[i-1] = lpszLine[i];
			}
			
			strcpy(targets[targetsInd].szCommand, command);
			free(command);
			targetsInd++;


		} 
		
		// encountered a target
		else {

			// skip if all whitespace
			if(lpszLine[0] == '\n' || lpszLine[0] == ' '){
				continue;
			}



			int tracking = 0;
			char* target;
			target = (char *) calloc(64, 1);
			char* dependencies;
			dependencies = (char *) calloc(640, 1);


			int count = 0;
			int j;
			j = 0;
			for(i = 0; lpszLine[i] != '\0'; i++){
				if(lpszLine[i] == ':'){
					count++;
					tracking = 1;
					strcpy(targets[targetsInd].szTarget, target);
					free(target);
					if (count == strlen(lpszLine)) {
						break;
					}
				}
				if(!tracking) {
					count++;
					target[i] = lpszLine[i];
				}
				if(lpszLine[i] == '#'){
					break;
				}
				if(tracking && lpszLine[i] != ':'){
					dependencies[j] = lpszLine[i];
					j++;
				}
			}

			i = 0;
			for(i = 0; i < 10; i++){
				deps[i] = (char *) calloc(64, 1);
			}
			char dependency[64];
		
			targets[targetsInd].nDependencyCount = 0;
			if (count != strlen(lpszLine)) {
				strcpy(dependency,strtok(dependencies, " "));
				i = 0;
				char* temp = "temp";

				while(temp != NULL) {
					// process the dependency
					// tokens are file names (e.g. util.a, main.o, etc.)
					strcpy(deps[i],dependency);

					temp = strtok(NULL, " ");
					if(temp){
						strcpy(dependency,temp);
					}
					targets[targetsInd].nDependencyCount++;
					i++;
				}


				// TODO: check syntax before adding to struct. If error encountered, quit.
				// return -1 if syntax error encountered
		
			} 

			// copy dependencies found for currently scanning target into target_t object
			for(i = 0; i < 10; i++) {
				strcpy(targets[targetsInd].szDependencies[i],deps[i]);
			}	


			free(dependencies);
			for(i = 0; i < 10; i++){
				free(deps[i]);
			}


		}


		//You need to check below for parsing.
		//Skip if blank or comment. +
		//Remove leading whitespace. +
		// Skip if whitespace-only. +
		// NOTE: Only single command is allowed.
		// TODO: If you found any syntax error, stop parsing. 
		// If lpszLine starts with '\t' it will be command else it will be target.
		// It is possbile that target may not have a command as you can see from the example on project write-up. (target:all)
		// You can use any data structure (array, linked list ...) as you want to build a graph
	}
	/*
	int i;
	int j;
	for(i = 0; i < 10 && *targets[i].szTarget; i++) {
		
		fprintf(stderr,"target: %s\n",targets[i].szTarget);
		fprintf(stderr,"d count: %d\n",targets[i].nDependencyCount);
		for(j = 0; j < 10 && *targets[i].szDependencies[j]; j++) {
			fprintf(stderr,"dependency #%d: %s\n",j+1,targets[i].szDependencies[j]);
		}
		fprintf(stderr,"command: %s\n\n",targets[i].szCommand);

	}
	*/
	//Close the makefile. 
	fclose(fp);

	return 0;
}
Exemplo n.º 11
0
int
config_load(const char *fileName,
            struct config **confOut)
{
   struct file_descriptor *fd;
   struct config *config;
   struct KeyValuePair *list;
   int res;

   *confOut = NULL;
   list = NULL;

   Log(LGPFX" Loading config '%s'\n", fileName);

   res = file_open(fileName, TRUE, FALSE, &fd);
   if (res != 0) {
      Log(LGPFX" Failed to open config '%s': %d\n", fileName, res);
      return res;
   }

   config = config_create();
   config->fileName = safe_strdup(fileName);
   config->list = list;

   while (TRUE) {
      char *line = NULL;
      char *key;
      char *val;
      bool s;

      res = file_getline(fd, &line);
      if (res != 0) {
         Log(LGPFX" Failed to getline: %d\n", res);
         goto fail;
      }
      if (line == NULL) {
         break;
      }

      s = config_parseline(line, &key, &val);
      free(line);
      if (!s) {
         Log(LGPFX" Failed to parseline: '%s'\n", line);
         res = -1;
         goto fail;
      }
      if (key == NULL) {
         /* comment in the config file */
         continue;
      }

      config_setunknownkv(config, key, val);
      free(key);
      free(val);
   }

   file_close(fd);

   *confOut = config;

   return res;

fail:
   config_freekvlist(list);
   file_close(fd);
   return res;
}
Exemplo n.º 12
0
void process_file(char* file_path, char* output_path){
	unsigned long id = pthread_self();
	char* dummy, *log_path, *out_fn, *out_path, *decrypted, *log_entry, *line;
	int out;
	//Create and initialize strings
	char id_string[512];
	log_path = malloc(512);
	out_fn = malloc(512);
	out_path = malloc(512);
	log_entry = malloc(512);
	decrypted = malloc(512);
	id_string[0] = '\0';
	log_path[0] = '\0';
	out_fn[0] = '\0';
	out_path[0] = '\0';
	log_entry[0] = '\0';
	decrypted[0] = '\0';

	//Construct the log filepath
	strcpy(log_path, output_path);
	strcat(log_path, "/log.txt");
	//Construct the .out filename and path
	strcpy(out_fn, get_fn(file_path));
	strcat(out_fn, ".out");
	strcpy(out_path, output_path);
	strcat(out_path, "/");
	strcat(out_path, out_fn);
	//Construct the log entry
	sprintf(id_string, "%lu", id);
	strcpy(log_entry, file_path);
	strcat(log_entry, ": ");
	strcat(log_entry, id_string);

	//Write to the log
	out = open(log_path, O_CREAT | O_WRONLY | O_APPEND, OPEN_2);
	if(out == -1){
		fprintf(stderr, "ERROR: open() failure\n");
	}
	write(out, log_entry, strlen(log_entry));
	write(out, "\n", sizeof(char));
	close(out);

	//Extract and decrypt the data
	FILE* fp = file_open(file_path);
	if(fp == NULL){
		fprintf(stderr, "WARN: filepath is invalid\n");
		return;
	}
	line = malloc(512);
	line[0] = '\0';
	file_getline(line, fp);
	decrypt(decrypted, line);

	//Write to the .out file
	out = open(out_path, O_CREAT | O_WRONLY | O_TRUNC, OPEN_2);
	if(out == -1){
		fprintf(stderr, "ERROR: open() failure\n");
	}
	write(out, decrypted, strlen(decrypted));
	close(out);

	//Free pointers
	free(line);
	free(log_path);
	free(out_path);
	free(out_fn);
	free(log_entry);
	free(decrypted);
}
Exemplo n.º 13
0
//This function will parse makefile input from user or default makeFile.
int parse(char * lpszFileName)
{
	int nLine=0;
	char szLine[1024];
	char * lpszLine;
	FILE * fp = file_open(lpszFileName);

	if(fp == NULL)
	{
		return -1;
	}

	/* This is not a simple initializer but an executable code */
	make406.current_id = 0;

	while(file_getline(szLine, fp) != NULL)
	{
		nLine++;
		// this loop will go through the given file, one line at a time
		// this is where you need to do the work of interpreting
		// each line of the file to be able to deal with it later

		//Remove newline character at end if there is one
		lpszLine = strtok(szLine, "\n");

		//Skip if blank or comment.
		if(szLine[0] == '#' || szLine[0] == '\n')
			continue;

		char **argvadr;
	       	int ntokens = makeargv(lpszLine, " ", &argvadr);
		//Remove leading whitespace.
		//Skip if whitespace-only.
		if(ntokens <= 0)
			continue;

		int curr = -1; /* Indicates the current line status */
		if(argvadr[0][strlen(argvadr[0]) - 1] != ':')  {
			fprintf(stderr, "%d line should be target", nLine);
			return -1;
		}
		curr = TARGET; /* We are right now in a target line */

		/* Initialize a node in the MakeTree*/
		target_t *node = malloc(sizeof(target_t));
		make406.nodelist[make406.current_id++] = node;

		/* TODO: push this node's target field. */
		strncpy(node->szTarget, argvadr[0], strlen(argvadr[0])-1);
		node->nDependencyCount = ntokens-1;
		int i;
		for(i=0; i<ntokens-1; ++i)
			strcpy(node->szDependencies[i], argvadr[i+1]);

		if(file_getline(szLine, fp) == NULL)  {
			fprintf(stderr, "%d line is missing", nLine);
			return -1;
		}
		nLine++;
		lpszLine = strtok(szLine, "\n");
		if((lpszLine[0] != '\t'))  {
			fprintf(stderr, "%d line should be command", nLine);
			return -1;
		}
		curr = COMMAND; /* We are currently in a command line */
		strcpy(node->szCommand, lpszLine);

		for(i = 0; i < ntokens; ++i)  {
			printf("\t%d\t%d\t%d\t%s\n", nLine, curr, ntokens, argvadr[i]);
		}

		//Only single command is allowed.
		//If you found any syntax error, stop parsing.
	}

	// Close the makefile.
	fclose(fp);

	// Printing out the nodes here.
	int i,j;
	i = 0;
	for( ; i<make406.current_id; ++i)  {
		printf("%s\n", make406.nodelist[i]->szTarget);
		j = 0;
		printf("no_dependencies: %d\n", make406.nodelist[i]->nDependencyCount);
		for( ; j < make406.nodelist[i]->nDependencyCount; ++j)
			printf("\t%s\n", make406.nodelist[i]->szDependencies[j]);
	}
	pid_t main_child_pid;
	int status = 0;
	generate_parsingtree(make406.nodelist[0], &main_child_pid);
	main_child_pid = waitpid(main_child_pid, &status, 0);
	return 0;
}
Exemplo n.º 14
0
//This function will parse makefile input from user or default makeFile. 
int parse(char * lpszFileName, char** defTarget)
{

	int nLine=0;
	char szLine[1024];
	char * lpszLine;
	FILE * fp = file_open(lpszFileName);

	if(fp == NULL)
	{
		return -1;
	}
	
	Node* nd;
	//This parsing is currently unfinished
	while(file_getline(szLine, fp) != NULL) 
	{
		static int firstNode = 1;
		static int lastTab = 1;
		nLine++;
		// this loop will go through the given file, one line at a time
		// this is where you need to do the work of interpreting
		// each line of the file to be able to deal with it later
		
		//Remove newline character at end if there is one
		lpszLine = strtok(szLine, "\n"); 
		//printf("%s\n",lpszLine);
		
		if(lpszLine == NULL)
			continue;
		
		if(lpszLine[0] == ' '){
			int i;
			for(i = 1; i<strlen(lpszLine); i++)
			{
				if(lpszLine[i] == '#')
				{
					break;
				}else if(lpszLine[i] != ' ')
				{
					printf("ERROR ERROR LINE INCORRECT SYNTAX \n");
					return -1;
				}
			}
			continue;
		}

		//check if comment
		if(lpszLine[0] == '#'){
			continue;
		}
		
		//if there is no tab, it's a target line
		if(lpszLine[0] != '\t')
		{
			if(lastTab == 0)
			{
				nd->command = " ";
				
				if(firstNode)
				{
					*defTarget = nd->target;
					//printf("WHAT IS THIS %s\n", *defTarget);

					list_item* new_item;
					if((new_item = (list_item *)malloc(sizeof(list_item))) == NULL)
					{	
						printf("ERROR: Insufficient memory\n");
						return -1;
					}

					new_item->item = (void *)nd;
					new_item->next = NULL;
					first = new_item;
					firstNode = 0;
				}else
				{
					list_item* new_item;
					if((new_item = (list_item *)malloc(sizeof(list_item))) == NULL)
					{	
						printf("ERROR: Insufficient memory\n");
						return -1;
					}
					
					new_item->item = (void *)nd;
					new_item->next = first;
					first = new_item;
				}
			}
			
			if((nd  = (Node*)malloc(sizeof(Node))) == NULL)
			{	
				printf("ERROR: Insufficient memory\n");
				return -1;
			}
			nd->toParent = NULL;
			nd->numTargetDep = 0;
			//look for colon
			char* col = strchr(lpszLine, ':');
		
			if(col != NULL)
			{					
				//copy target
				if((nd->target = (char *)malloc(((int)(col - lpszLine)) * sizeof(char))) == NULL)
				{	
					printf("ERROR: Insufficient memory\n");
					return -1;
				}
				
				strncpy(nd->target, lpszLine, (int)(col - lpszLine));

				nd->sizeDepends = 0;
				
				int sizeDep = strlen(col);
				
				int j;
				for(j = 1; j < sizeDep; j++)
				{
					if((col[j] != ' ') && ((col[j-1] == ' ') || (col[j-1] == ':')))
						nd->sizeDepends++;
				}

				//copy dependencies
				//Problem here for no dependencies?
				if((nd->dependencies = (char **)malloc(nd->sizeDepends * sizeof(char*))) == NULL)
				{	
					printf("ERROR: Insufficient memory\n");
					return -1;
				}

				int i = 0;
				int k = 0;
				for(i = 1; i < sizeDep; i++)
				{
					if((col[i] != ' ') && ((col[i-1] == ' ') || (col[i-1] == ':')))
					{
						char* end = strchr(&col[i], ' ');
						if(end != NULL)
						{
							if((nd->dependencies[k] = (char *)malloc(((int)(end - &col[i])) * sizeof(char))) == NULL)
							{	
								printf("ERROR: Insufficient memory\n");
								return -1;
							}
							strncpy(nd->dependencies[k], &col[i], ((int)(end - &col[i])));
							k++;
						}else if(i<sizeDep)
						{
							if((nd->dependencies[k] = (char *)malloc((sizeDep - i) * sizeof(char))) == NULL)
							{	
								printf("ERROR: Insufficient memory\n");
								return -1;
							}
							strncpy(nd->dependencies[k], &col[i], (sizeDep - i));
							break;
						}
					}
				}

			}
			
			lastTab = 0;
			
		}
		if(lpszLine[0] == '\t')
		{
			//this is a command, so copy the whole line
			
			if((nd->command = (char*)malloc(strlen(lpszLine+1)*sizeof(char))) == NULL)
			{
				printf("ERROR: Insufficient memory\n");
				return -1;
			}
			
			strcpy(nd->command, lpszLine+1);
			
			//add node to the front of the global linked list
			if(firstNode)
			{
				*defTarget = nd->target;
				
				list_item* new_item;
				if((new_item = (list_item *)malloc(sizeof(list_item))) == NULL)
				{	
					printf("ERROR: Insufficient memory\n");
					return -1;
				}

				new_item->item = (void *)nd;
				new_item->next = NULL;
				first = new_item;
				firstNode = 0;
			}else
			{
				list_item* new_item;
				if((new_item = (list_item *)malloc(sizeof(list_item))) == NULL)
				{	
					printf("ERROR: Insufficient memory\n");
					return -1;
				}

				new_item->item = (void *)nd;
				new_item->next = first;
				first = new_item;
			}
			
			lastTab = 1;
			
		}

		//You need to check below for parsing. 
		//Skip if blank or comment.
		//Remove leading whitespace.
		//Skip if whitespace-only.
		//Only single command is allowed.
		//If you found any syntax error, stop parsing. 
		//If lpszLine starts with '\t' it will be command else it will be target.
		//It is possbile that target may not have a command as you can see from the example on project write-up. (target:all)
		//You can use any data structure (array, linked list ...) as you want to build a graph

	}

	//Close the makefile. 
	fclose(fp);

	return 0;
}
Exemplo n.º 15
0
/**
 * Parses the file dependencies. For each dependency, places a pointer to the correct dependency in the target
 */
TARGET* parse_dependencies(char* filename)
{
	char* line = malloc(160*sizeof(char));
	FILE* fp = file_open(filename);
	
	char* token;
	bool getCmds   		= false;
	bool getDep    		= false;
	DEP* dependency	 	= NULL;	
	TARGET* tar		= NULL;
		

	//TODO: Uneccessarily goes through whole file
	while((line = file_getline(line, fp)) != NULL)
	{
		
		if(strncmp(line, "#", 1) != 0) //line isnt a commnet
		{
			fprintf(stdout, "Line: %s\n", line);
			if(getCmds)
			{
				if(strncmp(line, "}", 1) == 0)
				{
					//put node into tree
					getCmds = false;
					
				}
				else
				{								
					
				}
			}
			else
			{
				token = strtok(line, " :\n");

				dependency = (DEP*)malloc(sizeof(DEP));
		
				if(token != NULL) {fprintf(stdout, "Getting Tokens: \n");}

				while(token != NULL)
				{
					fprintf(stdout, "Token:[%s]\n", token);
					if(strpbrk(token, "{") != NULL)
					{
							//done taking in dependencies
							getCmds = true;
							getDep = false;
							fprintf(stdout, "--Done getting Tokens\n");
					}
					else if(getDep)//looking at deps
					{
						//Get a pointer to the target that the dep is referring too
						dependency->dep = find(token);

						if(dependency->dep == NULL) //dep doesnt exist
						{
							fprintf(stdout, "Dependency(%s) does not exist\n", token);
						}
						else //add dep to the target
						{
							dependency->dep_name = (char*)malloc(strlen(token));
							strcpy(dependency->dep_name, 
								 token);							
							fprintf(stdout, "Adding Dependency(%s) to %s-->",dependency->dep->name, 
															tar->name);
							tar->dependencies = add_Dnode(dependency, tar->dependencies);	
							if(strcmp(tar->dependencies->dep->name, token) == 0)
							{
								fprintf(stdout, "Success\n\n"); 
								dependency = (DEP*)malloc(sizeof(DEP));
							}
							else
							{
								fprintf(stdout, "Failire\n\n");
							}
						}						
					}	
					else //looking at target
					{				
						getDep = true;
						tar = find(token); //get a pointer to the target that was previously made
						
						if(tar == NULL)
						{
							fprintf(stderr,"(%s) is not in the target list\n", token);
						}

					}
					token = strtok(NULL, " \n");
				}
				
			}	
		}
	}
	print_targets();
	fclose(fp);
	free(line);
	return root;
}
Exemplo n.º 16
0
/**
 * Parse the make file and returns the root, containg the targets and their commands. Ignores dependencies
 */
TARGET* parse_targets(char* filename)
{
	char* line = malloc(160*sizeof(char));
	FILE* fp = file_open(filename);
	
	char* token;
	bool getCmds   		= false;
	bool getDep    		= false;
	TARGET* curr_tar 	= NULL;	
		

	while((line = file_getline(line, fp)) != NULL)
	{
		
		if(strncmp(line, "#", 1) != 0) //line isnt a commnet
		{
			fprintf(stdout, "Line: %s\n", line);
			if(getCmds)
			{
				if(strncmp(line, "}", 1) == 0)
				{
					//put node into tree
					getCmds = false;
					fprintf(stdout, "Adding Target(%s) to root --> ", curr_tar->name);
					root = add_Tnode(curr_tar, root);
					if(strcmp(root->name, curr_tar->name) == 0) {fprintf(stdout, "Success\n\n");}
					else{fprintf(stderr, "Failure\n");return NULL;}	
				}
				else
				{	
					//Pull command
					char* temp = strtok(line, ",\t\n"); 
					//This removes newlines and tabs and allows for extra credit	
					while(temp != NULL)
					{
						
						fprintf(stdout, "Pulling command: (%s) --> ", temp);
						curr_tar->commands = add_Cnode(temp, curr_tar->commands);
						if(curr_tar->commands == NULL){
							fprintf(stderr, "Add CNode failed\n");
							return NULL;
						}
						else if(strcmp(curr_tar->commands->command, temp) == 0)
						{
							fprintf(stdout, "Success\n\n");
						}
						else
						{
							fprintf(stderr, "Failure\n");return NULL;
						}							
						
						temp = strtok(NULL, "\n");
					}				
						
									
					
				}
			}
			else
			{
		
				curr_tar = (TARGET*)malloc(sizeof(TARGET));
				curr_tar->dependencies = NULL;
				token = strtok(line, " :\n");
				if(token != NULL) {fprintf(stdout, "Getting Tokens: \n");}

				while(token != NULL)
				{
					fprintf(stdout, "Token:[%s]\n", token);
					if(strpbrk(token, "{") != NULL)
					{
							//done taking in dependencies
							getCmds = true;
							getDep = false;
							fprintf(stdout, "--Done getting Tokens\n");
					}
					else if(getDep)
					{
						fprintf(stdout, "--Dependency\n");
						
					}	
					else //looking at target
					{			
						//Create the target node;	
						getDep = true;
						fprintf(stdout, "Pulling targetname: %s --> ", token);
						curr_tar->name = (char*)malloc(sizeof(strlen(token)));
						strncpy(curr_tar->name, token, strlen(token));
						if(strcmp(curr_tar->name, token) == 0){fprintf(stdout, "Success\n");}
						else{fprintf(stderr, "Failure\n");return NULL;}

					}
					token = strtok(NULL, " \n");
				}
				
			}	
		}
	}
	fclose(fp);
	free(line);
	return root;


}