简体   繁体   中英

How to copy a .txt file to a char array in c++

Im trying to copy a whole .txt file into a char array. My code works but it leaves out the white spaces. So for example if my .txt file reads "I Like Pie" and i copy it to myArray, if i cout my array using a for loop i get "ILikePie"

Here is my code

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () 
{
  int arraysize = 100000;
  char myArray[arraysize];
  char current_char;
  int num_characters = 0;
  int i = 0;

  ifstream myfile ("FileReadExample.cpp");

     if (myfile.is_open())
        {
          while ( !myfile.eof())
          {
                myfile >> myArray[i];
                i++;
                num_characters ++;
          }      

 for (int i = 0; i <= num_characters; i++)
      {

         cout << myArray[i];
      } 

      system("pause");
    }

any suggestions? :/

With

myfile >> myArray[i]; 

you are reading file word by word which causes skipping of the spaces.

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.

How this works

std::string has range constructor that copies the sequence of characters in the range [first,last) note that it will not copy last , in the same order:

template <class InputIterator>
  string  (InputIterator first, InputIterator last);

std::istreambuf_iterator iterator is input iterator that read successive elements from a stream buffer.

std::istreambuf_iterator<char>(in)

will create iterator for our ifstream in (beginning of the file), and if you don't pass any parameters to the constructor, it will create end-of-stream iterator (last position):

The default-constructed std::istreambuf_iterator is known as the end-of-stream iterator. When a valid std::istreambuf_iterator reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator. Dereferencing or incrementing it further invokes undefined behavior.

So, this will copy all characters, starting from the first in the file, until the next character is end of the stream.

Use the following code snippet:

FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);

char *string = (char *)malloc(fsize + 1);
fread(string, fsize, 1, f);
fclose(f);

string[fsize] = 0;

A simple solution if you're bound to using char arrays, and minimal modification to your code. The snippet below will include all spaces and line breaks until the end of the file.

      while (!myfile.eof())
      {
            myfile.get(myArray[i]);
            i++;
            num_characters ++;
      }  

A much simpler approach would be using the get() member function:

while(!myfile.eof() && i < arraysize)
{
    myfile.get(array[i]); //reading single character from file to array
    i++;
}

Here is the code snippet you need:

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


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

  str.c_str();

  for( unsigned int a = 0; a < sizeof(str)/sizeof(str[0]); a = a + 1 )
  {
    std::cout << str[a] << std::endl;
  }

  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM