歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux服務器 >> linux與windows回車換行問題

linux與windows回車換行問題

日期:2017/3/2 16:56:06   编辑:Linux服務器

所謂回車、換行這些控制符,都是從以前的電傳打字機的控制命令繼承下來的。回車就是打印頭復位,換行就是走紙。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,"\0");
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");

 
  後者默認的文件打開方式是文本方式,這時系統自動對文本進行了轉換,就不能得到上述的結論

Copyright © Linux教程網 All Rights Reserved