У меня есть код для чтения из файла
Я поднял файл в http://m.uploadedit.com/b026/13886560748.txt
размер строки в файле больше, чем 113, но ниже напечатанного кода 113
Зачем?!
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <bitset>
#include <stdlib.h>
using namespace std;
int main()
{
ifstream inf("Sample.txt");
string str;
string file_contents ="";
while ( getline(inf, str ) )
{
file_contents += str;
file_contents.push_back('\n');
}
cout << file_contents.size() << endl; // print 113
return 0;
}
UPDATE 1
Поэтому, открыв файл в двоичном режиме, проблема будет решена.
изменить ifstream inf("Sample.txt");
к ifstream inf("Sample.txt",ios::binary);
Вы читаете строки за строкой, соединяя их вместе с '\n'
, но преобразование двоично-текстового текста может быть на вашем месте envirnoment: в текстовом файле определенная ОС представляет собой "новую строку" с CR/LF (окна ) или LF/CR (mac os), а не только LF (linux).
Это приводит к тому, что файл больше, чем на самом деле.
std::ifstream inf("13886560748.txt", std::ios::binary);
Если вы хотите прочитать его пополам, это не лучший способ.
вы можете попробовать использовать ifstream read
#include <iostream>
#include <string>
#include <fstream>
#include <ios>
using namespace std;
//takes char to write byte to, and the current stream
//returns true if successfully read, else return false (aka. no more bytes to read)
bool readChar(unsigned char &r,ifstream &data){
if(data.read((char*)&r,sizeof(unsigned char))){
return true;
}
return false;
}
int main(){
ifstream sampleStream("Sample.txt",ios::binary|ios::in);
unsigned char tmp;
int byteCount = 0;
while (readChar(tmp,sampleStream))
{
byteCount++;
//If you'd like to read bits, use some bit masking here over tmp
//and iterate over bits
}
cout<<byteCount<<endl; // yields 6715
}
unsigned char
?