Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <unistd.h>
- int crcount(char *fbuffer_p) {
- int count = 0;
- for (int i = 0; fbuffer_p[i]; ++i) {
- switch (fbuffer_p[i]) {
- case '\n':
- ++count;
- break;
- case '\r':
- i += count += 1;
- }
- }
- return count;
- }
- void unixtodos(FILE *file_fp, const char *dest) {
- if (!file_fp) {
- fprintf(stderr, "Couldnt get a file descriptor for \"%s\"\n", dest);
- exit(1);
- }
- char chunkbuffer_p[8192];
- char outfilebuffer_p[8192];
- long int bytes_read;
- while ((bytes_read = fread(chunkbuffer_p, 1, 8192, file_fp))) {
- for (int i = 0, j = 0; chunkbuffer_p[i]; ++i) {
- if (chunkbuffer_p[i] == '\n') {
- outfilebuffer_p[j++] = '\r';
- outfilebuffer_p[j++] = '\n';
- } else
- outfilebuffer_p[j++] = outfilebuffer_p[i];
- }
- file_fp = freopen(dest, "a", file_fp);
- fwrite(outfilebuffer_p, 1, bytes_read, file_fp);
- file_fp = freopen(dest, "r", file_fp);
- }
- if (fclose(file_fp) == EOF) {
- fprintf(stderr, "Failed to close file: \"%s\"\n", dest);
- exit(2);
- }
- }
- void dostounix(FILE *file_p, const char *dest) {
- if (!file_p) {
- fprintf(stderr, "Couldnt get a file descriptor for \"%s\"\n", dest);
- exit(1);
- }
- fseek(file_p, 0L, SEEK_END);
- int fsize = ftell(file_p);
- if ((fseek(file_p, 0L, SEEK_SET))) {
- fprintf(stderr, "Failed to reset file pointer for \"%s\"\n", dest);
- exit(1);
- }
- char *fbuffer_p = malloc(fsize);
- fread(fbuffer_p, 1, fsize, file_p);
- const int NEW_SIZE = fsize - (crcount(fbuffer_p) / 2);
- char *outfilebuffer_p = malloc(NEW_SIZE);
- int j = 0;
- for (int i = 0; fbuffer_p[i]; ++i) {
- if (fbuffer_p[i] != '\r')
- outfilebuffer_p[j++] = fbuffer_p[i];
- }
- file_p = freopen(dest, "w", file_p);
- fwrite(outfilebuffer_p, 1, j, file_p);
- if (fclose(file_p) == EOF) {
- fprintf(stderr, "Failed to close file: \"%s\"\n", dest);
- exit(2);
- }
- }
- int main(int argc, const char **argv) {
- if (argc > 3) {
- fputs("Too many arguments", stderr);
- return 1;
- }
- if (strstr(*argv, "u2d"))
- unixtodos(fopen(argv[1], "r"), argv[1]);
- else
- dostounix(fopen(argv[1], "r"), argv[1]);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement