I have the following program in C, which is intended to convert UNIX text files to Windows format (LF->CR LF). Basically the intended usage is addcr infile > outfile
in the command line:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *fp;
char *buffer;
int i, flen;
if(argc<2)
{
printf("Usage: addcr filename\n");
return 0;
}
fp=fopen(argv[1], "r");
if(fp==NULL)
{
printf("Couldn't open %s.\n", argv[1]);
return 0;
}
fseek(fp, 0, SEEK_END);
flen=ftell(fp);
rewind(fp);
buffer=(char*)malloc(flen+1);
fread(buffer, 1, flen, fp);
fclose(fp);
buffer[flen]=0;
for(i=0;i < strlen(buffer);i++)
{
if(buffer[i]==0x10)
{
printf("%c", '\r');
}
printf("%c", buffer[i]);
}
free(buffer);
return 0;
}
However, sometimes it prints out garbage at the end of the file contents, as indicated by comparing its output to the TYPE command:
C:\Temp>addcr sample.txt
He did not wear his scarlet coat,
For blood and wine are red,
And blood and wine were on his hands
When they found him with the dead,
The poor dead woman whom he loved,
And murdered in her bed.
Window
C:\Temp>type sample.txt
He did not wear his scarlet coat,
For blood and wine are red,
And blood and wine were on his hands
When they found him with the dead,
The poor dead woman whom he loved,
And murdered in her bed.
C:\Temp>
It appears to sometimes print out some unpredictable portion of a string in my Environment Variables. I have absolutely no clue what could be causing it. Does anyone know how to resolve this problem?