2
int main()
{
char ch;
char text[500];
char s[500];

ifstream fin("bitch.txt",ios::in);
while(!fin.eof())
{
fin.getline(s,500);
}
fin.close();

for (int i=0; i<500; i++)
{
   cout << s[i];
}
return 0;
}

How to copy a whole text file contents into a char array in c++ considering the text file contains a 100 characters long paragraph I need to read the spaces too .

Sooraj S
  • 281
  • 5
  • 13

2 Answers2

2

Just do this

#include <string>
#include <fstream>
#include <streambuf>

std::ifstream file("file.txt");
std::string str((std::istreambuf_iterator<char>(file)),
                 std::istreambuf_iterator<char>());

Then

str.c_str();

Is the array that you seek.

Ed Heal
  • 55,822
  • 16
  • 77
  • 115
0

If you want to copy the full content of file into the char array, you dont need to do it line by line. You can just copy the full content of file

You can read entire file into the string with

std::ifstream in("FileReadExample.cpp");
std::string contents((std::istreambuf_iterator<char>(in)), 
std::istreambuf_iterator<char>());

And then you can use contents.c_str() to get char array

Look at the link below. he has given proper answer How to copy a .txt file to a char array in c++

Community
  • 1
  • 1
Pankaj Bansal
  • 829
  • 1
  • 12
  • 31