Форум » C/C++ для начинающих (C/C++ for beginners) » #include <iost.. » Ответить

#include <iost..

ramees: [pre2] #include <iostream> #include <fstream> #include <string> #include <limits> using namespace std; std::fstream& GotoLine(std::fstream&File, unsigned int num){ File.seekg(std::ios::beg); for (int i = 0; i < num - 1 ; i++){ File.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } return File; } int main(){ char *buf; string str1 = "abababab"; string str2 = "wjwjwjwjwjwj"; string str3 = "vivivivivivivivi"; int size1 = (str1.size()); int size2 = (str2.size()); int size3 = (str3.size()); string inp; int TS = 0; ofstream output("output.bin", ios::out | ios::binary); if (!output) { cout << "can't open file" << endl; exit(1); } for (int a = 1; a <= 3; a++){ if (a == 1){ inp = str1; TS = (str1.size()); } if (a == 2){ inp = str2; TS = (str2.size()); } if (a == 3){ inp = str3; TS = (str3.size()); } output.write(reinterpret_cast<char *>(&TS), sizeof(int)); output.write(inp.c_str(), TS); } str1 = str2 = str3 = ""; size1 = size2 = size3 = 0; TS = 0; output.flush(); output.close(); //======================================================================= ifstream input("output.bin", ios::in | ios::binary); if (!output) { cout << "can't open file" << endl; exit(1); } //for (int i = 0; i <= 3; i++){ // if (i == 1){ TS = (str1.size()); } // if (i == 2){ TS = (str2.size()); } // if (i == 3){ TS = (str3.size()); } // input.read(reinterpret_cast<char *>(&TS), sizeof(int)); // buf = new char[TS]; // input.read(buf, TS); // str1 = ""; // str1.append(buf, TS); // cout << str1 << endl; // //} fstream File("output.bin"); GotoLine(File, 1); string a; File >> a; cout << a << endl; return 0; }[/pre2] I created a function to access line in but only one line is returning If i put 1in GotoLine(File, 1); its return but anything grater than 1 is not working

Ответов - 4

Сыроежка: Function write does not append the new line character to output data. So function GotoLine does not make sense. Take into account that the internal representation of an integer can contain the new line character.

ramees: So ur saying that my output.bin file data saving in one line . How can i add a new line in output i am sorry i dont understand the last thing u said I already tried but i am getting error

Сыроежка: I meant that internal binary representation of a number can contain the bits combination that corresponds to the internal representation of the new line character. So when you deal with binary files you should not rely on the new line character. To read records you need to read at first the stored integer number that represents the length of the following string and then read the string itself to get the start of the next record.


ramees: Okay now i got it thanks



полная версия страницы