Actually, I only need the one from UNIX to DOS, that is, '\n' -> '\r\n'
With the help of sed, the following way can achieve the effect:
However, now I want to ask if there is a simpler method, preferably without using third-party tools.
I already know the principle. The following is excerpted from: http://hi.baidu.com/dbsuit/blog/item/511eb409f9abe7266b60fba8.html
[ Last edited by honghunter on 2008-1-10 at 02:15 PM ]
With the help of sed, the following way can achieve the effect:
sed -e "s/$/\r/" myunix.txt > mydos.txt However, now I want to ask if there is a simpler method, preferably without using third-party tools.
I already know the principle. The following is excerpted from: http://hi.baidu.com/dbsuit/blog/item/511eb409f9abe7266b60fba8.html
Conversion between Windows/DOS and Unix file formats
2007-06-21 13:25
Windows/DOS and Unix file formats are different
First, clarify a few symbols
*******************
0A LF ^J Newline
0D CR ^M Carriage return
*******************
In DOS/Windows text files, CR (carriage return \r) and LF (newline \n) are used.
In the case of the end of a line in the file, it is '\r\n'
Unix text only uses the newline character, with a newline (\n) at the end of the line, that is, '\n'
So C programs edited under Windows and compiled under Unix will have a "No end of newline" Warning
Conversion between the two file formats
Unix -> Dos
'\n' -> '\r\n'
//////////////////////////////////////////
while ( (ch = fgetc(in)) != EOF )
{
if ( ch == '\n' )
putchar('\r');
putchar(ch);
}
//////////////////////////////////////////
Just add a '\r' character before the '\n' that appears in the Unix file
Unix <- DOS
'\n' <- '\r\n'
The situation from Dos to Unix is more complicated. You can't just remove the '\r' read from the file.
Because there may be an embedded carriage return symbol at the end of the text line in the Dos file, this situation occurs in impact printers.
So before conversion, you need to judge whether '\r' and '\n' appear simultaneously.
If they appear simultaneously, remove '\r'
If they do not appear simultaneously, keep '\n'
//////////////////////////////////////////
cr_flag = 0; /* No CR encountered yet */
while ( (ch = fgetc(in)) != EOF )
{
if ( cr_flag && ch != '\n' ) {
/* This CR did not preceed LF */
putchar('\r');
}
if ( !(cr_flag = (ch == '\r')) )
putchar(ch);
}
//////////////////////////////////////////
[ Last edited by honghunter on 2008-1-10 at 02:15 PM ]

