Last active
January 26, 2022 11:44
-
-
Save UplinkCoder/5f79795ee2a7375c98c563303c3fdf59 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> // for fopen, fread, fwrite and fclose | |
| #include <string.h> // for memset and strcmp | |
| int main(int argc, char* argv[]) | |
| { | |
| if (argc != 3) | |
| { | |
| fprintf(stderr, "Usage: %s <src_file> <dest_file>\n", argv[0]); | |
| return 1; | |
| } | |
| // TODO make robust check for same file | |
| /* | |
| * #include <sys/stat.h> | |
| * | |
| */ | |
| if (0 == strcmp(argv[1], argv[2])) | |
| { | |
| fprintf(stderr, "src and dest must not be the file\n"); | |
| return 1; | |
| } | |
| FILE* r_fd = fopen(argv[1], "rb"); | |
| FILE* w_fd = fopen(argv[2], "wb"); | |
| #define READ_BUFFER_SIZE 1024 | |
| #define WRITE_BUFFER_SIZE (READ_BUFFER_SIZE * 4) | |
| char read_buffer[READ_BUFFER_SIZE]; | |
| char write_buffer[WRITE_BUFFER_SIZE]; | |
| unsigned int write_pos = 0; | |
| unsigned int bytes_read = 0; | |
| bytes_read = fread(read_buffer, 1, 1024, r_fd); | |
| int lastNonWhiteSpace = 0; | |
| int line = 1; | |
| int col = 0; | |
| while (bytes_read) | |
| { | |
| for(unsigned int i = 0; i < bytes_read; i++) | |
| { | |
| col++; | |
| char c = read_buffer[i]; | |
| if (c == '\t') | |
| { | |
| memset(write_buffer + write_pos, ' ', 4); | |
| write_pos += 4; | |
| col += 4; | |
| } | |
| else | |
| { | |
| if (c == '\n') | |
| { | |
| // strip trailing whitespace | |
| int trailing_whitespace = ((col - 1) - lastNonWhiteSpace); | |
| if (trailing_whitespace) | |
| { | |
| // printf("%d bytes of trailing whitespace detected at: {%d, %d}\n", trailing_whitespace, line, lastNonWhiteSpace); | |
| } | |
| write_pos -= trailing_whitespace; | |
| line++; | |
| col = 0; | |
| lastNonWhiteSpace = 0; | |
| } | |
| else if (c != ' ') | |
| { | |
| lastNonWhiteSpace = col; | |
| } | |
| write_buffer[write_pos++] = c; | |
| } | |
| } | |
| fwrite(write_buffer, 1, write_pos, w_fd); | |
| bytes_read = fread(read_buffer, 1, 1024, r_fd); | |
| write_pos = 0; | |
| } | |
| fclose(w_fd); | |
| fclose(r_fd); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment