简体   繁体   English

如何在C ++中将.txt文件复制到char数组

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

Im trying to copy a whole .txt file into a char array. 我试图将整个.txt文件复制到char数组中。 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" 因此,例如,如果我的.txt文件读为“ I Like Pie”,然后将其复制到myArray,如果使用for循环退出数组,则会得到“ 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. 然后,您可以使用contents.c_str()获得char数组。

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: std::string具有范围构造器,该构造器将复制[first,last)范围内的字符序列, 请注意,它不会以相同顺序复制last

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迭代器是从流缓冲区中读取连续元素的输入迭代器。

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): 将为(文件的开头) ifstream in创建迭代器,并且如果您不向构造函数传递任何参数,它将创建流结束迭代器(最后一个位置):

The default-constructed std::istreambuf_iterator is known as the end-of-stream iterator. 默认构造的std :: istreambuf_iterator被称为流结束迭代器。 When a valid std::istreambuf_iterator reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator. 当有效的std :: istreambuf_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. 如果您必须使用char数组,这是一个简单的解决方案,并且对代码的修改最少。 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: 一个更简单的方法是使用get()成员函数:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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