Guest User

Untitled

a guest
Jan 17th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. /*
  2. Maggie Cao
  3. Uniq program prints out the uniq lines data from a file input using
  4. delimiters and strcpy of the original buffer. Max buffer size for read is
  5. 1024 bytes.
  6. */
  7. #define _GNU_SOURCE
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <sys/types.h>
  12. #include <unistd.h>
  13. #include <errno.h>
  14. #include <fcntl.h>
  15. #include <unistd.h>
  16. #include <sys/stat.h>
  17. #define MAX 1024
  18. #define MAXBUFFER 1024 //max number of bytes allowed to be read in a file
  19.  
  20. char **split(char *);
  21.  
  22. /*splits char*buffer that was read into an array of strings*/
  23. char **split(char *input){
  24.  
  25. char **argv = calloc(MAX, sizeof(char*) );
  26.  
  27. /*allocate space for each string*/
  28. int j;
  29. for (j=0; j<MAX; j++)
  30. argv[j]=malloc(MAX*(sizeof(char)));
  31.  
  32. //char *delim= " \t\n";
  33. char *delim= "\n";
  34. int i=0;
  35. argv[i]= strtok(input, delim);
  36.  
  37. while (argv[i]!=NULL){
  38. i++;
  39. argv[i] = strtok(NULL, delim);
  40. }
  41.  
  42. argv[i+1]=NULL;
  43.  
  44. return argv;
  45. }
  46. int main (int argc, char *argv[]){
  47.  
  48. int fd, numread,writeread;
  49. char buffer[MAXBUFFER];
  50. fprintf(stdout,"usage: ./a.out file.txt \n");
  51.  
  52. fd=open(argv[1],O_RDONLY);
  53. if (fd==-1){
  54. perror("can't open file");
  55. exit(EXIT_FAILURE);
  56. }
  57.  
  58.  
  59. int i=0;
  60. int newlines=0;
  61. while((numread=read(fd, buffer, sizeof(buffer))) != 0){
  62. //Display the characters read
  63. writeread=write(1,buffer,numread);
  64. }
  65.  
  66. char *newbuffer=malloc(writeread*(sizeof(char)));
  67. strcpy(newbuffer,buffer);
  68.  
  69. //fprintf(stdout, "new truncated string at bytesread length:\n%s", newbuffer);
  70.  
  71. char *newbuffer1=malloc(writeread*(sizeof(char)));
  72. strcpy(newbuffer1,buffer);
  73.  
  74. /*find out number of lines in the file*/
  75. char *delim="\n";
  76. char *token;
  77. token=strtok(newbuffer1,delim);
  78. while (token!=NULL){
  79. newlines++;
  80. token=strtok(NULL,delim);
  81. }
  82.  
  83. fprintf(stdout, "numlines total is %d \n", newlines);
  84.  
  85. char **buffersplit=split(newbuffer);
  86. int k=0;
  87. /*prints uniq lines to standard output*/
  88. while (k<(newlines-1)){
  89. strstr(buffersplit[k], buffersplit[k+1]);
  90. if (strstr(buffersplit[k], buffersplit[k+1]) == NULL){
  91. write(1,buffersplit[k],strlen(buffersplit[k]));
  92. fprintf(stdout, "\n");
  93. }
  94. k++;
  95. }
  96.  
  97. close(fd);
  98. free(buffersplit);
  99. free(newbuffer);
  100. free(newbuffer1);
  101. return 0;
  102. }
Add Comment
Please, Sign In to add comment