#include
#include
int main() {
std::ifstream file("example.txt"); // open the file
if (!file) { // check if the file was opened successfully
std::cout << "Unable to open file";
return 1;
}
file.seekg(0, std::ios::end); // move to the end of the file
int fileSize = file.tellg(); // get the file size
file.seekg(0, std::ios::beg); // move back to the beginning of the file
char* charArray = new char[fileSize + 1]; // allocate memory for the char array
file.read(charArray, fileSize); // read the entire file into the char array
charArray[fileSize] = '\0'; // null-terminate the char array
// do something with the char array
std::cout << charArray << std::endl;
delete[] charArray; // deallocate memory
file.close(); // close the file
return 0;
}
Мой примерный код:
Я пробую через eof посчитать длину файла, с которого считываю. Записываю количество символов в переменную count.
Создаю массив char с размерностью count.
Пытаюсь из строки записать данные в массив при помощи цикла while.
Но в итоге выходит полная краказябра. Метод seekg использовать нельзя. Как быть?
std::ifstream fin;
fin.open ("file.txt");
int count = 0;
while (!fin.eof()) {
char ch;
fin >> ch;
count++;
}
cout << count;
char* fromFile = new char[count];
int i = 0;
while (i<count) {
char ch;
fin >> ch;
fromFile[i] = ch;
i++;
}
for (int i = 0; i < count; i++) {
cout << fromFile[i];
}
fin.close();
delete[] fromFile;
}