Unix에서 Windows로 변환 할 때 정확한 결과를 얻습니다. 그러나 Windows에서 Unix로 갈 때 이상한 결과를 얻습니다. 내가 허용해야했던 것은 캐리지 리턴 '\ r'을 제거하는 것 뿐이라고 생각했습니다. 이것은 비록 작동하지 않습니다. 코드를 실행 한 후 텍스트 파일을 열면 몇 가지 이상한 결과가 나타나고 첫 번째 줄이 올 바르며 모든 지옥이 끊어집니다.텍스트 파일을 Windows에서 Unix로 변환하는 방법
int main()
{
bool windows = false;
char source[256];
char destination[256]; // Allocate the max amount of space for the filenames.
cout << "Please enter the name of the source file: ";
cin >> source;
ifstream fin(source, ios::binary);
if (!fin) // Check to make sure the source file exists.
{
cerr << "File " << source << " not found!";
getch();
return 1;
}//endif
cout << "Please enter the name of the destination file: ";
cin >> destination;
ifstream fest(destination);
if (fest) // Check to see if the destination file already exists.
{
cout << "The file " << destination << " already exists!" << endl;
cout << "If you would like to truncate the data, please enter 'Y', "
<< "otherwise enter 'N' to quit: ";
char answer = char(getch());
if (answer == 'n' || answer == 'N')
{
return 1;
}//endif
}//endif
clrscr(); // Clear screen for neatness.
ofstream fout(destination, ios::binary);
if (!fout.good()) // Check to see if the destination file can be edited.
{
cout << destination << "could not be opened!" << endl;
getch();
return 1;
}//endif
// Open the destination file in binary mode.
fout.open(destination, ios::binary);
char ch = fin.get(); // Set ch to the first char in the source file.
while (!fin.eof())
{
if (ch == '\x0D') // If ch is a carriage return, then the source file
{ // must be in a windows format.
windows = true;
}//endif
if (windows == true)
{
ch = fin.get(); // Advance ch, so that at the bottom of the loop, the
}//endif // carriage return is not coppied into the new file.
if (windows == false)
{
if (ch == '\x0A') // If the file is in the Unix format..
{
fout.put('\x0D'); // When a new line is found, output a carriage
}//endif // return.
}//endif
fout.put(ch);
ch = fin.get();
}//endwh
if (windows == true)
{
fout.put('\x0A');
}//endif
fout.close();
fin.close(); // Close yer files.
if (windows == true) // A little output for user-friendly-ness.
{
cout << "The contents of " << source << " have been coppied to "
<< destination << " and converted to Unix format." << endl;
}else{
cout << "The contents of " << source << " have been coppied to "
<< destination << " and converted to Windows format." << endl;
}//endif
cout << "Enter any key to quit.." << endl;
getch();
return 0;
}//endmn
그래서, 다른 방향으로 어떻게됩니까? –
스크립트를 사용할 수 있으면 linux/unix 플랫폼에서 dos2unix를 사용할 수도 있습니다. – weima
이 경우 문제가 될지는 모르지만 실제로 fest를 호출해야합니다.close()'를 호출하여 대상 파일의 입력 스트림을 닫은 다음 출력 스트림으로여십시오. –