When a file is moved between Linux and Windows, the file edited in Windows always displays a ^ m in each line when Linux is opened. Although this does not affect the usage, it affects the appearance, so I want to implement a small program for conversion.
To implement the conversion, you must first understand why the above situation occurs. For details, it is because of the operating system's historical reasons. Simply put, the line break of Windows is carriage return + line feed, while that of Linux is line feed, therefore, files in Windows will display the carriage return at the end of the line as ^ m in Linux.
After understanding the cause of the problem, the following is the code. The idea is simple and I will not explain it.
1 #include <sys/time.h> 2 #include <iostream> 3 #include <fstream> 4 #include <string> 5 #include <string.h> 6 7 using namespace std; 8 9 void usage()10 {11 cout << "Please input like this:" << endl;12 cout << "WinToLinux oldfile newfile" << endl;13 }14 15 int main(int argc, char **argv)16 {17 unsigned int timeuse;18 struct timeval stStartTime;19 struct timeval stEndTime;20 21 usage();22 23 gettimeofday(&stStartTime, NULL);24 25 if(argc != 3)26 {27 cout << "Parameter is not deserved!" << endl;28 return -1;29 }30 31 ifstream fin(argv[1]);32 ofstream fout(argv[2]);33 34 if(!fin.is_open())35 {36 cout << "Open file failed,please check your file path." << endl; 37 }38 39 string strTmp;40 while(getline(fin, strTmp))41 {42 if(strTmp[strTmp.size() -1 ] == ‘\r‘)43 {44 strTmp.erase(strTmp.size() - 1, 1);45 }46 fout << strTmp << endl;47 strTmp.clear();48 }49 50 gettimeofday(&stEndTime, NULL);51 timeuse = 1000000*(stEndTime.tv_sec - stStartTime.tv_sec) + 52 stEndTime.tv_usec - stStartTime.tv_usec;53 cout << "Use time : " << timeuse/1000000.0 << " sec" << endl;54 55 return 0;56 }
Programming must be applied, and useful code can be valuable.
Remove ^ m