【发布时间】:2014-02-12 04:36:25
【问题描述】:
我有以下 C 语言程序,旨在将 UNIX 文本文件转换为 Windows 格式 (LF->CR LF)。基本上预期的用法是命令行中的addcr infile > outfile:
#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;
}
但是,有时它会在文件内容的末尾打印出垃圾,这可以通过将其输出与 TYPE 命令进行比较来表明:
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>
它似乎有时会在我的环境变量中打印出一些不可预测的字符串部分。我完全不知道是什么原因造成的。有谁知道如何解决这个问题?
【问题讨论】:
标签: c console text-files line-endings