我有一个名为“ Sample.dat ”的文件,其中包含以下内容:
This is line 1
This is line 2
This is line 3
This is line 4
当我尝试使用std::ifstream::binary
模式读取 WITHOUT 文件时,输出错误。代码:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
int main()
{
std::ifstream inf("F:\\cpp_programming\\File_Input_Output\\Sample.dat");
if(!inf)
{
std::cerr << "Uh oh, Sample.dat could not be opened!" << std::endl;
exit(1);
}
std::string str1;
inf.seekg(5);
std::getline(inf, str1);
std::cout << str1 << std::endl;
inf.seekg(8, std::ios::cur);
std::getline(inf, str1);
std::cout << str1 << std::endl;
inf.seekg(-15, std::ios::end);
std::getline(inf, str1);
std::cout << str1 << std::endl;
return 0;
}
输出(不正确)是:
is line 1
e 2
his is line 4
使用std::ifstream::binary
模式时输出正确。代码:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
int main()
{
std::ifstream inf("F:\\cpp_programming\\File_Input_Output\\Sample.dat", std::ifstream::binary);
if(!inf)
{
std::cerr << "Uh oh, Sample.dat could not be opened!" << std::endl;
exit(1);
}
std::string str1;
inf.seekg(5);
std::getline(inf, str1);
std::cout << str1 << std::endl;
inf.seekg(8, std::ios::cur);
std::getline(inf, str1);
std::cout << str1 << std::endl;
inf.seekg(-15, std::ios::end);
std::getline(inf, str1);
std::cout << str1 << std::endl;
return 0;
}
输出(正确)是:
is line 1
line 2
his is line 4
为什么二进制模式会给出正确的输出?