Untitled
#include "header.h" header *create_header(struct stat sb, char *path){ struct header *curr_header; char *size8_buff, *size12_buff, *header_field; size_t path_len; int i; /* Initialize header and string buffers */ curr_header = malloc(sizeof(header)); size8_buff = malloc(sizeof(char) * 8); size12_buff = malloc(sizeof(char) * 12); /* Check if malloc failed */ if(curr_header == NULL || size8_buff == NULL || size12_buff == NULL){ perror("malloc"); exit(EXIT_FAILURE); } path_len = strlen(path); /* Pack name and prefix fields */ if(path_len >= MAX_NAME_LEN){ perror("file name too long"); return NULL; } else if(path_len < NAME_SIZE){ /* If name fits in name block */ if((curr_header->name = strdup(path)) == NULL){ perror("strdup"); exit(EXIT_FAILURE); } curr_header->prefix = NULL; } else if(path_len == NAME_SIZE){ /* If name is exactly 100 chars decide if it goes in prefix or name */ for(i = 0; i < NAME_SIZE; i++){ if(path[i] == '\0'){ curr_header->name = NULL; if((curr_header->prefix = strdup(path)) == NULL){ perror("strdup"); exit(EXIT_FAILURE); } } else if(path[i] == '/'){ if((curr_header->name = strdup(path)) == NULL){ perror("strdup"); exit(EXIT_FAILURE); } curr_header->prefix = NULL; break; } } } else{ /* ADD SPLIT NAME FUNCTION */ } /* Write mode as an octal num and store in header */ header_field = duplicate_buff(size8_buff); if(snprintf(header_field, MODE_SIZE, "%0o", sb.st_mode) < 0){ perror("word overflow"); } curr_header->mode = header_field; /* Write uid as an octal num and store in header */ header_field = duplicate_buff(size8_buff); if(snprintf(header_field, UID_SIZE, "%0o", sb.st_uid) < 0){ perror("word overflow"); } curr_header->uid = header_field; /* Write gid as an octal num and store in header */ header_field = duplicate_buff(size8_buff); if(snprintf(header_field, GID_SIZE, "%0o", sb.st_gid) < 0){ perror("word overflow"); } curr_header->gid = header_field; /* Write size as an octal num and store in header */ header_field = duplicate_buff(size12_buff); if(snprintf(header_field, FILESIZE_SIZE, "%0o", sb.st_size) < 0){ perror("word overflow"); } curr_header->size = header_field; /* Write mtime as an octal num and store in header */ header_field = duplicate_buff(size12_buff); if(snprintf(header_field, MTIME_SIZE, "%0o", sb.st_mtime) < 0){ perror("word overflow"); } curr_header->mtime = header_field; if(S_ISREG(sb.st_mode)){ curr_header->typeflag = '0'; } else if(S_ISDIR(sb.st_mode)){ curr_header->typeflag = '5'; } else if (S_ISLNK(sb.st_mode)){ curr_header->typeflag = '2'; } else{ curr_header->typeflag = '\0'; } /* ADD LINKNAME */ curr_header->magic = "ustar"; curr_header->version = "00"; /* ADD CHKSUM */ free(size8_buff); free(size12_buff); return curr_header; } char *duplicate_buff(char *buff){ char *header_field; /* Duplicate buff and exit on failure */ if((header_field = strdup(buff)) == NULL){ perror("strdup"); exit(EXIT_FAILURE); } return header_field; }
Leave a Comment