\r to \r\n converter
Well though this is not an advanced topic, and just simple malloc()s, for()'s, free()'s and we're
done, but it's an interesting topic, I think.
I do most of my coding on Notepad, and frankly speaking it simply r0x! It's clean and it's fast,
but a damn problem is that Unix editors understand \n's, and notepad doesn't understand \n, and
therefore everything appears to be in one line, and you have to use something like word pad to
cure that, DAMN!
Anyway, I'll discuss here how to convert all \n's to \r's. Of course if there is a \r preceding \n
we have to ignore that, and it also checks if the file is \r\n'ed already.
Here's the code, it's ANSI code :
#include <stdio.h>
#include <malloc.h>
int main (int argc, char **argv)
{
/* usage: rn filename1 filename2 filename3 [...] */
FILE *fp;
int i, x, r, bytes_written, bytes_read, filesize;
char *read_data, *gnu_data;
/* let's loop through the arguements */
for (r = 1; r <= argc; r++)
{
if (argv[r] == NULL) { continue; } /* just go on if it's NULL */
if ((fp = fopen(argv[r], "rt")) == NULL)
{
printf("unable to open %s for reading. skipping...\n", argv[r]);
continue;
} /* ofcourse fopen is relative to the dir in which the program runs */
if (fseek(fp, 0, SEEK_END) != 0)
{
printf("unable to seek through %s. skipping...\n", argv[r]);
continue;
} /* this is just to determine the filesize of the the file */
if ((filesize = (int)ftell(fp)) == (long)-1)
{
printf("unable to determine filesize for %s. skipping...\n", argv[r]);
continue;
} /* and it's the only way i know :-) */
if (fseek(fp, 0, SEEK_SET) != 0)
{
printf("unable to rewind file pointer for %s. skipping...\n", argv[r]);
continue;
} /* and so let's get back to square #1 */
read_data = (char *)malloc(filesize); /* allocate memory for the file */
gnu_data = (char *)malloc(2 * filesize); /* allocate twice as much memory */
bytes_read = fread(read_data, sizeof(char), filesize, fp);
fclose(fp);
if (bytes_read != filesize)
{
free(read_data);
free(gnu_data);
printf("%s is already (\\r\\n)'d. skipping...\n", argv[r]);
continue;
} /* yes this a VALID check, read the man pages, and you'll see why :-) */
/* the exchange point */
for (i = 0, x = 0; i < filesize; i++, x++)
{
if ((read_data[i] == '\n') && (read_data[(i-1)] != '\r'))
{
gnu_data[x] = '\r';
gnu_data[(x+1)] = '\n';
x++;
continue;
}
gnu_data[x] = read_data[i];
}
if ((fp = fopen(argv[r], "wt")) == NULL) {
free(read_data);
free(gnu_data);
printf("unable to open %s for writing. skipping...\n", argv[r]);
continue;
}
if ((bytes_written = fwrite(read_data, sizeof(char), filesize, fp)) != filesize) {
free(gnu_data);
free(read_data);
printf("only %d btyes written to %s...\n", bytes_written, argv[r]);
continue;
}
/* let's free up the data */
free(read_data);
free(gnu_data);
printf("%s has been (\\r\\n)'d successfuly...\n", argv[r]);
}
return 0;
}
Rate this article