linux与windows回车换行问题
点击次数:36 次 发布日期:2008-11-21 23:26:48 作者:源代码网
|
源代码网推荐
所谓回车、换行这些控制符,都是从以前的电传打字机的控制命令继承下来的。回车就是打印头复位,换行就是走纸。Dos/Windows和Unix/Linux对回车、换行的理解差别就在于Dos/Windows认为0d=0d0a=0a,而Unix/Linux坚持沿用电传打字机的工作方式(这个其实是比较正确的)。 所以在回车换行在Linux中是"0d",在Windows中是"0d0a".我们可以通过下面的程序测试一下:
CODE:
#define MAX_LENGTH 15536 #include #include using namespace std; string delEnter(const string src) // 过滤掉串中的回车换行符 { string des; for(int i = 0; i < src.length(); i++) { char tempChar = src[i]; if( tempChar!=10 && tempChar!=13) des.append(1,tempChar); } return des; } int main() { char html[MAX_LENGTH] = ""; FILE *fp = fopen("Linux.txt", "rb"); //FILE *fp = fopen("Windows.txt", "rb"); char buf[16384]; while (fgets(buf, 16384, fp)) strcat(html, buf); strcat(html," "); string s(html); cout << "string is: " << s << endl;; cout << "The size of string is: " << s.length() << endl; cout << "after del string is: " << delEnter(s) << endl; cout << "The size of string is: " << delEnter(s).length() << endl; fclose(fp); return 0; }
程序中文件Linux.txt是从Linux系统中copy过来的。我们可以通过这个程序观察到,通过过滤掉回车换行符,Linux文件中的字符数的减少等于其行数,而 Windows中等于其行数的两倍。但有一个问题要注意,程序中行: CODE: FILE *fp = fopen("Linux.txt", "rb"); 不能写成: FILE *fp = fopen("Linux.txt", "r");
后者默认的文件打开方式是文本方式,这时系统自动对文本进行了转换,就不能得到上述的结论
源代码网供稿. |