Guest User

remove_spaces.c

a guest
Jan 11th, 2021
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.42 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4. #include <sys/stat.h>
  5. #include <sys/mman.h>
  6.  
  7. char* remove_spaces_asm16(char *in, char *out, unsigned int count);
  8.  
  9. char* remove_spaces_straight(char* in, char* out, unsigned int count) {
  10.     while (count--) {
  11.         if (*in != ' ') {
  12.             *out++ = *in;
  13.         }
  14.         in++;
  15.     }
  16.     return out;
  17. }
  18.  
  19. int main(int argc, char **argv) {
  20.     if (argc < 2) {
  21.         printf("Usage: %s <file> [asm]\n", argv[0]);
  22.         exit(0);
  23.     }
  24.  
  25.     int fd;
  26.     struct stat fs;
  27.    
  28.     fd = open(argv[1], O_RDONLY);
  29.     if (fd < 0) {
  30.         printf("Error opening file \"%s\"\n", argv[1]);
  31.         exit(1);
  32.     }
  33.    
  34.     fstat(fd, &fs);
  35.     printf("File size: %li\n", fs.st_size);
  36.     if (fs.st_size % 16) {
  37.         fputs("File size must be divisible by 16\n", stderr);
  38.         exit(1);
  39.     }
  40.    
  41.     char *in = mmap(NULL, fs.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
  42.     char *out = malloc(fs.st_size);
  43.     char *end;
  44.    
  45.     if (argc > 2) {
  46.         end = remove_spaces_asm16(in, out, fs.st_size);
  47.         printf("Spaces found (asm): %li\n", fs.st_size - (end - out));
  48.         out[22] = '\0';
  49.         printf("\"%s\"\n", out);
  50.     } else {
  51.         end = remove_spaces_straight(in, out, fs.st_size);
  52.         printf("Spaces found (straight): %li\n", fs.st_size - (end - out));
  53.         out[22] = '\0';
  54.         printf("\"%s\"\n", out);
  55.     }
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment